使用反射访问特性
来源:互联网 发布:js textarea 不可编辑 编辑:程序博客网 时间:2024/06/05 01:48
如果没有检索自定义特性的信息和对其进行操作的方法,则定义自定义特性并将其放置在源代码中就没有意义。 使用反射,可检索用自定义特性定义的信息。 主要方法是 GetCustomAttributes,它返回对象数组,这些对象在运行时等效于源代码特性。 此方法具有多个重载版本。 有关更多信息,请参见Attribute。 特性规范,如
[Author("P. Ackerman", version = 1.1)]
class SampleClass
在概念上等效于:
anonymousAuthorObject.version
下面是一个完整的示例。 定义一个自定义特性,将其应用于若干实体并通过反射进行检索。
// Multiuse attribute.
[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;
// Default value.
version = 1.0;
}
public string GetName()
{
return name;
}
}
// Class with the Author attribute.
[Author("P. Ackerman")]
public class FirstClass
{
// ...
}
// Class without the Author attribute.
public class SecondClass
{
// ...
}
// Class with multiple Author attributes.
[Author("P. Ackerman"), Author("R. Koch", version = 2.0)]
public class ThirdClass
{
// ...
}
class TestAuthorAttribute
{
static void Test()
{
PrintAuthorInfo(typeof(FirstClass));
PrintAuthorInfo(typeof(SecondClass));
PrintAuthorInfo(typeof(ThirdClass));
}
private static void PrintAuthorInfo(System.Type t)
{
System.Console.WriteLine("Author information for {0}", t);
// Using reflection.
System.Attribute[] attrs = System.Attribute.GetCustomAttributes(t); // Reflection.
// Displaying output.
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);
}
}
}
}
/* Output:
Author information for FirstClass
P. Ackerman, version 1.00
Author information for SecondClass
Author information for ThirdClass
R. Koch, version 2.00
P. Ackerman, version 1.00
*/
- 使用反射访问特性
- 使用反射访问特性
- C#使用反射访问特性
- 使用反射特性获取类的访问权限
- C#反射,特性结合使用
- 使用反射、特性简化代码
- C# 使用反射访问属性
- 使用Java5特性来简化反射编程
- 如何使用自定义特性和反射?
- 使用Java5特性来简化反射编程
- 使用Java5特性来简化反射编程
- 使用Java5特性来简化反射编程
- 使用Java5特性来简化反射编程
- 使用Java5特性来简化反射编程
- C#反射,特性,数据库结合使用
- c# 特性/属性(Attribute) 以及使用反射查看自定义特性
- c# 特性/属性(Attribute) 以及使用反射查看自定义特性
- C#使用反射访问私有构造函数
- 关于linux下mmap的一点强调
- Hibernate ID 生成策略
- ASP.NET下CKEditor和CKFinder集成 配置
- 有关MAC、PHY和MII
- poj 1503 Integer Inquiry高精度
- 使用反射访问特性
- 气质的培养(哈佛管理世界)除了沉稳外很适合研发人员借鉴
- JSOI 2008-help
- Android布局之LinearLayout(线性布局)
- symbian程序安装时兼容第三版和第五版
- 如何使用Delphi编写Modbus RTU CRC16的校验码
- jquery之浏览器的事件模型(DOM 0级事件模型)
- 自定义数字排序(方法一)
- 我在Centos5.6 上安装支持802.11b g的无线网卡驱动的具体过程