C#获取属性

注意 如何从System.Attribute类中继承 以及如何使用构造函数和属性来定义attribute参数
可以在VB类中使用该attribute 方法如下
<Author("Julian")>
Public Class Fred
...
End Class
在C++中 可以使用attribute的 attribute 来创建一个托管类或者结构
以代表一个自定义attribute 注意这个类不必从System.Attribute中继承

[attribute(target)]
public __gc class Author {
...
};
如果 attribute 要用于其他 assembly那么类必须是公共的target
参数是System.AttributeTargets 枚举的一个参数 如前面表 2.5 所示 在 attribute 类中 构造函数用于指定位置参数 而数据成员和属性则用于实现命名参数 下面是Author attribute的C++代码
[attribute(Class)] public __gc class Author { String *authorName; // positional parameter String *lastModDate; // named parameter public: __property String* get_Name () { return authorName; } __property String* get_ModDate () { return lastModDate; } __property String* set_ModDate (String* date) { lastModDate = date; } Author(String* name) { authorName = name; } }; 可以将该attribute加入到一个类中 如下所示 [Author("Julian", Date="21/12/00")] public __gc class Foo { }; 可以看到 因为Data是一个命名参数 它由关键字指定 并且位于参数列表的末尾 在C#中 创建attribute的方法是类似的 但有两点不同 [AttributeUsage(AttributeTargets.Class)] public class Author : System.Attribute { private string authorName; // positional parameter private string lastModDate; // named parameter 第2章 .NET编程模型 71 public string Name { get { return authorName; } } public string ModDate { get { return lastModDate; } set { lastModDate = value; } } Author(string name) { authorName = name; } }; 第一个区别是 attribute类从System.Attribute继承而来 而C++中则不需要任何继承第二个区别是 attributeusage attribute用于控制该attribute的使用范围 除此之外 代码在结构上是很类似的 使用构造函数实现位置参数 使用属性实现命名参数

2.2.19 查询attribute
尽管大多数attribute都由编译器创建 并由CLR使用 但是有时候程序员还需要知道某些项处理特定attribute的范围 并且能够检查这些attribute 为了找到有关 attribute 需要了解 System.Type 类 Type 是表示类 接口 属性 值类型以及枚举等类型定义的一种类 它能够找出许多关于类型及其属性的详细信息 但是 用户只需要知道如何使用类来获取这些attribute信息即可 注意 如果了解C++ 可以考虑使用RTTI将会有所帮助 下面考察 VB中是如何检索attribute信息的实例 并对该代码进行分析 仍然使用前一节的Author attribute实例 <Author("Julian", Date="21/12/00")> Public Class Foo ... End Class 获得一个Type对象以表示Foo类 而后查询该类 可以知道Foo类是否具有一个Author attribute

在C#中实现该操作几乎是完全相同的

using System;
...
Type tf
= typeof(Foo);
object[] atts = tf.GetCustomAttributes(true);
foreach(object o in atts) {
if(o.GetType().Equals(typeof(Author)))
Console.WriteLine(
"Foo has an Author attribute");
}

第一件事就是 使用Typeof操作符获取一个所要查询的类的Type对象
而后可以使用GetCustomAttributes()方法来获取一组该对象所支持的自定义attribute的引用列表
因为将返回普通对象引用的数组 因此需要检查对象的类型 以确认它们中是否有 Author 项
注意GetType()方法的使用 它将从对象引用中返回一个 Type 对象
这与 typeof 操作符相对应后者从类名称中返回一个 Author 属性
一旦对该类找到了一个 Author 属性 就可以检索该参数

原文地址:https://www.cnblogs.com/wucg/p/1766256.html