是这个意思么? protected void Page_Load(object sender, EventArgs e) { Type t = typeof(A); System.Reflection.PropertyInfo[] ps = t.GetProperties(); foreach (System.Reflection.PropertyInfo p in ps) { if (p.GetCustomAttributes(false).Length > 0) { foreach (object o in p.GetCustomAttributes(false)) { if (o is MyPro) { Response.Write(p.Name + " ============="); } } } }
} public class A { string _S1; string _S2; public string S1 { get { return _S1; } set { _S1 = value; } } [MyPro] public string S2 { get { return _S2; } set { _S2 = value; } } } public class MyPro : Attribute {
我理解这段代码实现的作用是:在定义类时通过自定义特性来附加上一些信息用来描述这个类.这些信息是否放在codecheckerattribute生成的实例中呢,还有就是如果多个类都采用类MyPro标记,那么后一个用MyPro 标记的类中的信息是否会覆盖前一个用MyPro标记的信息 [MyPro(x,x,x=x)] class A { ... } [MyPro(xx,xx,xx=xx)] class B { ... } 是否会存在用反射获取类A中的信息,得到的却是类B中的信息(覆盖). 不知道这样的理解是否正确..
{ Type t = typeof(A);
System.Reflection.PropertyInfo[] ps = t.GetProperties();
foreach (System.Reflection.PropertyInfo p in ps)
{
if (p.GetCustomAttributes(false).Length > 0)
{
foreach (object o in p.GetCustomAttributes(false))
{
if (o is MyPro)
{
Response.Write(p.Name + " =============");
}
}
}
}
} public class A
{
string _S1;
string _S2; public string S1
{
get
{
return _S1;
}
set
{
_S1 = value;
}
} [MyPro]
public string S2
{
get
{
return _S2;
}
set
{
_S2 = value;
}
}
} public class MyPro : Attribute
{
}
//定义一个可以使用在类上面的特性类。
//用这个特性可以在类上做标记,这里是做一个代码检查的标记
[AttributeUsage( AttributeTargets.Class)]
public class CodeCheckerAttribute : Attribute
{
private string reviewer; //检查代码的人
private string date; //检查时间
private string comment; //注释 public CodeCheckerAttribute(string reviewer, string date)
{
this.reviewer = reviewer;
this.date = date;
} public string Reviewer
{
get { return this.reviewer; }
}
public string Date
{
get { return this.date; }
}
public string Comment
{
get { return this.comment; }
set { this.comment = value; }
}
} //使用特性标记这个类
[CodeChecker("Jeff", "2008-7-19", Comment="not completed")]
public class MyClass
{
public MyClass(){ }
}
//我想知道某个类的代码谁检查过没?利用反射得到这些信息。
private void button1_Click(object sender, EventArgs e)
{
System.Reflection.MemberInfo info = typeof(MyClass);
CodeCheckerAttribute att = (CodeCheckerAttribute)Attribute.GetCustomAttribute(info, typeof(CodeCheckerAttribute));
if (att != null)
{
string ss = att.Reviewer + '\n' + att.Date + '\n' + att.Comment;
MessageBox.Show(ss);
}
}
自定义特性:http://www.cnblogs.com/zhouyinhui/archive/2006/10/02/520240.html
至于自定义特性:
http://www.cnblogs.com/thinhunan/archive/2005/11/30/287648.html
去自己看看这个帖子,还是比较经典的
cnblog看看!!
但是为什么要这样用呢...还是没发现这种用法的优势.
标记的类中的信息是否会覆盖前一个用MyPro标记的信息
[MyPro(x,x,x=x)]
class A
{
...
}
[MyPro(xx,xx,xx=xx)]
class B
{
...
}
是否会存在用反射获取类A中的信息,得到的却是类B中的信息(覆盖).
不知道这样的理解是否正确..
首先A和B的区分有很多方法,
2.如果不能区分,Myrpo这个自定义属性也可以加参数的.
问题是我不知道这中技巧在编程过程中在哪个领域用的比较频繁.大家能不贴些
代码给我.....