反射不承认该类是继承的C#

时间:2015-06-03 19:53:33

标签: c# inheritance reflection attributes

我的问题是我想从自定义属性中获取数据,我不知道使用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;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

只需更改此行:

foreach(Attribute.GetCustomAttributes中的var a( typeof(cl1)))

foreach(Attribute.GetCustomAttributes中的var a( this.GetType()))