美文网首页ABP
C#特性 3(应用)

C#特性 3(应用)

作者: 北风知我意 | 来源:发表于2018-08-14 14:47 被阅读53次

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

一、运用范围

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

按 Ctrl+C 复制代码

[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();

    }

  }

按 Ctrl+C 复制代码

这里我们给出了除了程序集和模块以外的常用的Atrribute的定义。 

二、自定义Attribute

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

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

按 Ctrl+C 复制代码

[AttributeUsage(AttributeTargets.Property)]

public class StringLengthAttribute : Attribute

{

  private int _maximumLength;

  public StringLengthAttribute(int maximumLength)

  {

    _maximumLength = maximumLength;

  }

  public int MaximumLength

  {

    get { return _maximumLength; }

  }

}

按 Ctrl+C 复制代码

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

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

按 Ctrl+C 复制代码

public class People

{

  [StringLength(8)]

  public string Name { get; set; }

  [StringLength(15)]

  public string Description { get; set; }

}

按 Ctrl+C 复制代码

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

第三步:创建验证的类

按 Ctrl+C 复制代码

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));

      }

    }

  }

}

按 Ctrl+C 复制代码

这里用到了反射,因为Attribute一般都会和反射一起使用,这里验证了字符串长度是否超过所要求的,如果超过了则会抛出异常

按 Ctrl+C 复制代码

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();

}

按 Ctrl+C 复制代码

希望本文所述实例对大家的C#程序设计能有一定的帮助作用。

相关文章

  • C#特性 3(应用)

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

  • C#语言特性发展史

    C#语言特性发展史 Intro 本文主要总结介绍C# 每个版本带来的不同的语言特性。 C#,读作C Sharp,是...

  • C#特性(Attribute)-现学现用

    前言 想要灵性的使用C#反射机制,特性(Attribute)的使用是必不可少的。 C# 特性(Attribute)...

  • C#网络应用编程.pdf

    【下载地址】 《C#网络应用编程(第2版)》主要介绍如何用C#开发Windows窗体网络应用程序。全书分3部分,第...

  • C#枚举类型常用扩展方法(三)

    C#获取枚举值特性(Display、Description、自定义特性) 一、Display特性 调用如下: 二、...

  • 目录 - C#

    总目录 C# 第01局:泛型 C# 第02局:反射 C# 第03局:特性 C# 第04局:委托 C# 第05局:事...

  • C#反射与特性应用实例

    应用场景:1用SQL语句从数据库返回一个DataTable对象,2然后绑定到DataGridView控件上,Dat...

  • C# 语言历史版本特性(C# 1.0到C# 8.0汇总)

    C# 1.0 特性Classes:面向对象特性,支持类类型Structs:结构Interfaces:接口Event...

  • C# 特性

    泛型 无 lambda表达式 无 匿名函数 无 委托 winfrom界面委托 在对控件进行操作的时候,可以通过判断...

  • c#特性

    c#特性: 特性(Attribute)是用于在运行时传递程序中的各种元素(比如类,方法,结构,枚举,组件等)的行为...

网友评论

    本文标题:C#特性 3(应用)

    本文链接:https://www.haomeiwen.com/subject/dzhvbftx.html