通过反射得到绑定在类的属性上的特性信息
来源:互联网 发布:java ee课件 编辑:程序博客网 时间:2024/05/21 10:22
标题够绕的 :)
using System;
using System.Reflection;
using System.Collections;
// 特性类
public class CoTestAttribute : Attribute
{
string m_attributeName1;
public string AttributeName1
{
get{return m_attributeName1;}
set{m_attributeName1 = value;}
}
}
// 正常类
public class CoTestClass
{
string m_classProperty1;
[CoTest(AttributeName1="attribute value")]
public string ClassProperty1
{
get{return m_classProperty1;}
set{m_classProperty1 = value;}
}
}
class MainClass
{
# region 正确结果
// 通过类型
Type classType1 = typeof(CoTestClass);
PropertyInfo PI1 = classType1.GetProperty("ClassProperty1");
object[] resultArray1 = PI1.GetCustomAttributes(typeof(CoTestAttribute), false);
CoTestAttribute result1 = resultArray1[0] as CoTestAttribute;
Console.WriteLine("得到正确信息: " + result1.AttributeName1);
Console.WriteLine();
// 通过实例
CoTestClass classInstance1 = new CoTestClass();
classInstance1.ClassProperty1 = "property value";
PropertyInfo instancePI = classInstance1.GetType().GetProperty("ClassProperty1");
object[] resultArray2 = instancePI.GetCustomAttributes(typeof(CoTestAttribute), false);
CoTestAttribute result2 = resultArray2[0] as CoTestAttribute;
Console.WriteLine("得到正确信息: " + result2.AttributeName1);
Console.WriteLine();
# endregion
# region 错误结果
// 通过类型
Type classType2 = typeof(CoTestClass);
object[] errorResult1 = classType2.GetCustomAttributes(typeof(CoTestAttribute), false);
if(errorResult1.Length == 0)
{
Console.WriteLine("未得到需要的信息!");
}
Console.WriteLine();
// 通过实例
CoTestClass classInstance2 = new CoTestClass();
classInstance2.ClassProperty1 = "property value";
object[] errorResult2 = classInstance2.GetType().GetCustomAttributes(typeof(CoTestAttribute), false);
if(errorResult2.Length == 0)
{
Console.WriteLine("未得到需要的信息!");
}
# endregion
Console.ReadLine();
}
- 通过反射得到绑定在类的属性上的特性信息
- java 通过反射机制得到类的属性和方法
- C#中的特性 和 通过反射获取属性上的特性
- 用反射+特性列出所有的枚举变量及其描述信息,绑定到DropDownList上
- c#通过反射获取类上的自定义特性
- c#通过反射获取类上的自定义特性
- c#通过反射获取类上的自定义特性
- 通过反射访问属性(Attribute)信息的工具类
- Java通过反射得到其属性的值包含父类属性
- 反射得到类的内部信息
- 通过反射,得到真实的类Demo
- [转]用反射+特性列出所有的枚举变量及其描述信息,绑定到DropDownList上。
- java反射得到类对象,并且得到类的属性
- C#中通过反射查看程序集的特性信息
- Java中通过反射获得对象的属性信息
- Java中通过反射获得对象的属性信息
- Java通过反射得到属性的值和设置属性的值
- 利用java的反射机制得到类的信息
- 俞敏洪:度过有意义的生命
- 关于Ext.grid.GridFilters和FusionCharts結合的使用 Javascript
- Android 技术专题系列之十七 -- volume 服务
- 无题
- LINUX 下 ipv6 socket 编程(转)
- 通过反射得到绑定在类的属性上的特性信息
- 读书笔记《Building Embeded Linux System》第九章建立Bootloader
- Android 技术专题系列之一 -- Android 是什么
- 一些基本的widgets
- Android 技术专题系列之二 -- telephony
- 浮动层JS类,兼容IE和Firefox
- Android 技术专题系列之三 -- 编译(build) 流程
- Android 技术专题系列之四 -- 网络资源及常见命令备
- Find out distributor and publisher info in Sql Server replication (摘)