我的问题是我想从自定义属性中获取数据,我不知道使用typeof()方法获取当前类型的算法。
[AttrN("test1")]
[AttrC("test2")]
public class cl2 :cl1 {
//should find attributes and set fields from base
public cl2() : base() { }
}
public class cl1 {
public string n;
public string c;
public cl1() {
setValuesFromCustomAttributes();
}
private void setValuesFromCustomAttributes() {
foreach (var a in Attribute.GetCustomAttributes(typeof(cl1))) {
setn(a);
setc(a);
}
}
private void setn(Attribute attr) {
if (attr is AttrNAttribute) {
var x = (AttrNAttribute)attr;
n= x.getString;
}
}
private void setc(Attribute attr) {
if (attr is AttrCAttribute) {
var x = (AttrCAttribute)attr;
c = x.getString;
}
}
}
答案 0 :(得分:0)
只需更改此行:
foreach(Attribute.GetCustomAttributes中的var a( typeof(cl1)))
到
foreach(Attribute.GetCustomAttributes中的var a( this.GetType()))