在c#中的属性类的构造函数中,如何判断正在处理的属性目标?

时间:2014-01-26 04:07:39

标签: c# custom-attributes

如果您有以下属性类:

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Class)]
public class MyValidationAttribute : Attribute
{
    public string Message { get; set; }

    public MyValidationAttribute()
    {
        // If this is decorating a property, do this
        if (this.DecoratesProperty)  // Of course this is totally made up
        {
            Message = "This is decorating a property";
        }
        else
        {
            Message = "This is decorating a class";
        }
    }
    ...
}

我只是用一种(非工作的)方式来询问这个装饰是否在一个属性上(而不是一个类)。但有没有办法做到这一点真实?

当然先谢谢。

1 个答案:

答案 0 :(得分:-1)

你可以通过构造函数参数告诉属性,在声明它的时候吗?

e.g;

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Class)]
public class TestAttribute : Attribute
{
    public TestAttribute(Type target)
    {
        if (target == typeof(object))
        {

        }
        else if (target == typeof(PropertyInfo))
        {

        }
    }
}

[TestAttribute(typeof(object))]
class SomeClass
{
    [TestAttribute(typeof(PropertyInfo))]
    public string SomeProperty { get; set; }
}