C#反射的GetCustomAttributes方法
来源:互联网 发布:安卓ui优化 编辑:程序博客网 时间:2024/06/04 08:48
使用反射访问属性(C# 编程指南)
如果没有检索自定义属性的信息和对其进行操作的方法,则定义自定义属性并将其放置在源代码中就没有意义。C# 具有一个反射系统,可用来检索用自定义属性定义的信息。主要方法是 GetCustomAttributes,它返回对象数组,这些对象在运行时等效于源代码属性。此方法具有多个重载版本。有关更多信息,请参见 Attribute。
属性规范,如:
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#
[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#反射的GetCustomAttributes方法
- c#反射中GetMethods()和GetCustomAttributes()方法
- C# 反射通过GetCustomAttributes方法,获得自定义特性
- C# 反射通过GetCustomAttributes方法,获得自定义特性
- C#的反射机制调用方法
- C#取代反射取值的方法
- C#泛型方法的反射
- C#反射方法学习
- c# 反射时GetType方法查找Type的分析
- C#项目引用完全相同dll文件的问题解决方法(反射)
- 在C#中使用反射调用internal的方法
- c# 通过反射回调Ajax请求的方法
- c#反射Type类型的一些方法介绍
- c#反射重载方法(发现不明确的匹配)
- C#项目引用完全相同dll文件的问题解决方法(反射)
- C# 利用反射调用类下的方法
- c#反射重载方法(发现不明确的匹配)
- C#反射的学习(二)--访问字段、属性、方法
- 没有可用于 ‘xxxxx’的编辑器,确保已安装文件类型(.xx)的应用程序
- 大话PHP之性能
- 断言失败-缺少资源 .
- XMODEM协议 .
- 关于inflaterect和deflaterect .
- C#反射的GetCustomAttributes方法
- VC:剪切板参考程序
- 画笔的使用 .
- iOS开发之缓存(一):内存缓存
- JS 玩玩cookie(设置过期时间)
- Jquery 开发插件的两种类型 之别插件开发
- 用U盘装Win7
- 关于Onsize中控件句柄为空的问题 .
- alarmManage使用