C#属性(Attribute)用法实例解析

属性(Attribute)是C#程序设计中很是重要的一个技术,应用范围普遍,用法灵活多变。本文就以实例形式分析了C#中属性的应用。具体入戏:javascript

1、运用范围html

程序集,模块,类型(类,结构,枚举,接口,委托),字段,方法(含构造),方法,参数,方法返回值,属性(property),Attributejava

复制代码
[AttributeUsage(AttributeTargets.All)]
  public class TestAttribute : Attribute
  {
  }
  [TestAttribute]//结构
  public struct TestStruct { }
   
  [TestAttribute]//枚举
  public enum TestEnum { }
 
 
  [TestAttribute]//类上
  public class TestClass
  {
    [TestAttribute]
    public TestClass() { }
     
    [TestAttribute]//字段
    private string _testField;
 
    [TestAttribute]//属性
    public string TestProperty { get; set; }
 
    [TestAttribute]//方法上
    [return: TestAttribute]//定义返回值的写法
    public string TestMethod([TestAttribute] string testParam)//参数上
    {
      throw new NotImplementedException();
    }
  }
复制代码

这里咱们给出了除了程序集和模块之外的经常使用的Atrribute的定义。 this

2、自定义Attributespa

为了符合“公共语言规范(CLS)”的要求,全部的自定义的Attribute都必须继承System.Attribute。设计

第一步:自定义一个检查字符串长度的Attribute3d

复制代码
[AttributeUsage(AttributeTargets.Property)]
public class StringLengthAttribute : Attribute
{
  private int _maximumLength;
  public StringLengthAttribute(int maximumLength)
  {
    _maximumLength = maximumLength;
  }
 
  public int MaximumLength
  {
    get { return _maximumLength; }
  }
}
复制代码

AttributeUsage这个系统提供的一个Attribute,做用来限定自定义的Attribute做用域,这里咱们只容许这个Attribute运用在Property上,内建一个带参的构造器,让外部传入要求的最大长度。code

第二步:建立一个实体类来运行咱们自定义的属性orm

复制代码
public class People
{
  [StringLength(8)]
  public string Name { get; set; }
 
  [StringLength(15)]
  public string Description { get; set; }
}
复制代码

定义了两个字符串字段Name和Description, Name要求最大长度为8个,Description要求最大长度为15.htm

第三步:建立验证的类

复制代码
public class ValidationModel
{
 
  public void Validate(object obj)
  {
    var t = obj.GetType();
 
    //因为咱们只在Property设置了Attibute,因此先获取Property
    var properties = t.GetProperties();
    foreach (var property in properties)
    {
 
      //这里只作一个stringlength的验证,这里若是要作不少验证,须要好好设计一下,千万不要用if elseif去连接
      //会很是难于维护,相似这样的开源项目不少,有兴趣能够去看源码。
      if (!property.IsDefined(typeof(StringLengthAttribute), false)) continue;
 
      var attributes = property.GetCustomAttributes();
      foreach (var attribute in attributes)
      {
        //这里的MaximumLength 最好用常量去作
        var maxinumLength = (int)attribute.GetType().
          GetProperty("MaximumLength").
          GetValue(attribute);
 
        //获取属性的值
        var propertyValue = property.GetValue(obj) as string;
        if (propertyValue == null)
          throw new Exception("exception info");//这里能够自定义,也能够用具体系统异常类
 
        if (propertyValue.Length > maxinumLength)
          throw new Exception(string.Format("属性{0}的值{1}的长度超过了{2}", property.Name, propertyValue, maxinumLength));
      }
    }
 
  }
}
复制代码

这里用到了反射,由于Attribute通常都会和反射一块儿使用,这里验证了字符串长度是否超过所要求的,若是超过了则会抛出异常

复制代码
private static void Main(string[] args)
{
    var people = new People()
    {
      Name = "qweasdzxcasdqweasdzxc",
      Description = "description"
    };
    try
    {
      new ValidationModel().Validate(people);
    }
    catch (Exception ex)
    {
      Console.WriteLine(ex.Message);
    }
    Console.ReadLine();
}
复制代码

但愿本文所述实例对你们的C#程序设计能有必定的帮助做用。

 

https://www.cnblogs.com/ldyblogs/p/attribute.html

相关文章
相关标签/搜索