我如何获得对象实例的注释或自定义属性?

时间:2015-12-01 22:54:32

标签: c# .net reflection

是否可以访问Object实例的Annotation定义?

让我说我有以下代码:

public class A
{
    [CustomStuff( Value="" )]
    public B propertyB;
}

在另一个类中,我收到一个B实例作为参数,是否可以从该对象获取注释?

1 个答案:

答案 0 :(得分:1)

不可能,能够做到这一点真的没有意义。注释是属性,而不是实例。举个例子:

public class A
{
    [CustomStuff( Value="Something" )]
    public B One;

    [CustomStuff( Value="SomethingElse" )]
    public B Two;

    [MoreCustom( Value="" )]
    public B One;
}

然后使用它:

var a = new A();
DoSomething(a.One);

public void DoSomething(B instance) 
{
    //What should the result be here?
    //Should be 'CustomStuff:Something', right?    
}

var a = new A();
a.Two = a.One
DoSomething(a.One);

//Now what should it be?

var a = new A();
a.Two = a.One
var tmp = a.One;
a.One = a.Two = null;
DoSomething(tmp);

//And now?