C#反射访问属性规范有哪些

本篇文章给大家分享的是有关C#反射访问属性规范有哪些,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

成都创新互联公司专注于延长企业网站建设,响应式网站,商城建设。延长网站建设公司,为延长等地区提供建站服务。全流程按需定制,专业设计,全程项目跟踪,成都创新互联公司专业和态度为您提供的服务

C#反射——属性规范

C#

[Author("H. Ackerman", version = 1.1)]  class SampleClass

在概念上等效于:

C#

Author anonymousAuthorObject = new Author("H. Ackerman");  anonymousAuthorObject.version = 1.1;

但是,直到查询 SampleClass 以获取属性时才会执行此代码。对 SampleClass 调用 GetCustomAttributes 会导致按上述方式构造并初始化一个 Author 对象。如果类还有其他属性,则其他属性对象的以类似方式构造。然后 GetCustomAttributes 返回 Author 对象和数组中的任何其他属性对象。之后就可以对此数组进行迭代,确定根据每个数组元素的类型所应用的属性,并从属性对象中提取信息。

C#反射——示例

下面是一个完整的示例。定义一个自定义属性,将其应用于若干实体并通过反射进行检索。

C#

[System.AttributeUsage(System.AttributeTargets.Class |                         System.AttributeTargets.Struct,                         AllowMultiple = true)  // multiuse attribute  ]  public class Author : System.Attribute  {      string name;      public double version;       public Author(string name)      {          this.name = name;          version = 1.0;  // Default value      }       public string GetName()      {          return name;      }  }   [Author("H. Ackerman")]  private class FirstClass  {      // ...  }   // No Author attribute  private class SecondClass  {      // ...  }   [Author("H. Ackerman"), Author("M. Knott", version = 2.0)]  private class ThirdClass  {      // ...  }   class TestAuthorAttribute  {      static void Main()      {          PrintAuthorInfo(typeof(FirstClass));          PrintAuthorInfo(typeof(SecondClass));          PrintAuthorInfo(typeof(ThirdClass));      }       private static void PrintAuthorInfo(System.Type t)      {          System.Console.WriteLine("Author information for {0}", t);          System.Attribute[] attrs = System.Attribute.GetCustomAttributes(t);  // reflection           foreach (System.Attribute attr in attrs)          {              if (attr is Author)              {                  Author a = (Author)attr;                  System.Console.WriteLine("   {0}, version {1:f}", a.GetName(), a.version);              }          }      }  }

输出

Author information for FirstClass

H. Ackerman, version 1.00

Author information for SecondClass

Author information for ThirdClass

H. Ackerman, version 1.00

M. Knott, version 2.00

以上就是C#反射访问属性规范有哪些,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注创新互联行业资讯频道。


分享名称:C#反射访问属性规范有哪些
标题路径:http://csdahua.cn/article/ipjchh.html
扫二维码与项目经理沟通

我们在微信上24小时期待你的声音

解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流