当前位置: 移动技术网 > IT编程>开发语言>c# > C#属性(Attribute)用法实例解析

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

2019年07月18日  | 移动技术网IT编程  | 我要评论
属性(attribute)是c#程序设计中非常重要的一个技术,应用范围广泛,用法灵活多变。本文就以实例形式分析了c#中属性的应用。具体入戏: 一、运用范围 程序集,模块

属性(attribute)是c#程序设计中非常重要的一个技术,应用范围广泛,用法灵活多变。本文就以实例形式分析了c#中属性的应用。具体入戏:

一、运用范围

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

[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的定义。 

二、自定义attribute

为了符合“公共语言规范(cls)”的要求,所有的自定义的attribute都必须继承system.attribute。

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

[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上,内建一个带参的构造器,让外部传入要求的最大长度。

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

public class people
{
  [stringlength(8)]
  public string name { get; set; }

  [stringlength(15)]
  public string description { get; set; }
}

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

第三步:创建验证的类

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#程序设计能有一定的帮助作用。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网