在c#如何用反射来解析自定义的attribute?

来源:学生作业帮助网 编辑:作业帮 时间:2024/05/04 14:33:56

在c#如何用反射来解析自定义的attribute?
在c#如何用反射来解析自定义的attribute?

在c#如何用反射来解析自定义的attribute?
你说的attribute 是属性还是特性
1.如果是特性:
用GetCustomAttributes()这个函数
比如建一个工程 加一个testAttr 的特性类和一个test类
public class testAttr : Attribute
{ public int i { get; set; }}
[testAttr(i = 123)]
public class test
{ }
我想得到i=123 的值,就随便一个单击事件里加代码 :
object [] obj= typeof(test).GetCustomAttributes(true);
MessageBox.Show((obj[0] as testAttr).i.ToString());
2.如果是自定义的属性:
类:
public class test
{
public int i { get; set; }
}
单击事件:
test t = new test();
t.i = 123;
MemberInfo mi = t.GetType().GetMember("i")[0];
MessageBox.Show( t.GetType().GetProperty("i").GetValue(t, null).ToString());