温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2021-06-24 14:28:43 来源:亿速云 阅读:138 作者:Leah 栏目:编程语言

本篇文章给大家分享的是有关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#反射访问属性规范有哪些,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI