c# - 从 BaseClass 中的子类获取自定义属性 (C# .NET 4.0)

标签 c# inheritance attributes custom-attributes

好的,编辑代码以进行澄清:

问题:如何从 BaseClass.TheAttribute 访问 TestClassOne/Two 中的属性 [MyAttr("...")] ...?

除 TestClassOne/Two 之外的所有类都将编译到我的“核心”中,并作为开发平台交付给客户。 TestClassOne/Two是客户自己开发的,所以“核心”中不可能有TestClassOne/Two的知识。

下面的代码被编译成“core”并作为dll交付给客户。

[TestMethod()]
public void AttrTest()
{
    var one = new TestClassOne();
    var attrOne = one.MyTestProperty.TheAttribute;

    var two = new TestClassTwo();
    var attrTwo = two.MyTestProperty.TheAttribute;
}

public class MyAttr : Attribute
{
    private string _test;
    public MyAttr(string test)
    {
        this._test = test;
    }
}

public class BaseClass
{
    public string TheAttribute
    {
        get { 
            // Here I would like to get the "[MyAttr("...")]" from the classes in the bottom

            return null;
        }
    }
}

public class SubClass : BaseClass
{

}

下面的代码是由客户开发的(使用我的 dll)

public class TestClassOne
{
    [MyAttr("Attribute one")]
    public SubClass MyTestProperty = new SubClass();
}

public class TestClassTwo
{
    [MyAttr("Attribute two")]
    public SubClass MyTestProperty = new SubClass();
}

最佳答案

您可以直接从类型Test获取:

var result = typeof (Test)
               .GetField("MyTest", BindingFlags.Public | BindingFlags.Instance)
               .GetCustomAttribute<MyAttr>();

关于c# - 从 BaseClass 中的子类获取自定义属性 (C# .NET 4.0),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12552646/

相关文章:

c# - 涉及 List<T> 和对象转换的棘手问题

python - 类内带下划线定义的变量

constructor - 使用私有(private)属性复制构造函数

javascript - 是否可以在 javascript 的子类的覆盖版本中使用父类的方法?

java - Xpath - 如何获取元素的所有属性名称和值

c# - 如何判断 BottomSheetDialogFragment 何时展开以填充屏幕?

c# - 由多个线程读取/写入的字段,Interlocked 与 volatile

c# - 在垃圾收集之前检测堆损坏

c# - 命令行参数

python - 通过继承连接类变量?