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

标签 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";
        }
    }
    ...
}

我只是想出了一个(无效的)方法来询问这个装饰是否在一个属性上(相对于一个类)。但有没有办法真正做到这一点?

当然先谢谢了。

最佳答案

你能在声明时通过构造函数参数告诉属性吗?

例如;

[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; }
}

关于c# - 在 C# 属性类的构造函数中,如何判断正在处理的属性目标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21359563/

相关文章:

c# - 检查整数是否为 0 并返回 bool 值的简短方法

c# - 无法打包 Microsoft 云服务项目,导致 "Could not load type ' Microsoft.Cct.Services.Sqm.IWatSqmService' 错误

c# - 如何删除所有表并重置 Azure SQL 数据库

html - 包含 <style amp-boilerplate> 的原因是什么

c# - 这是否违反了开闭原则?

C# 到 Mono GetConsoleWindow 异常

c# - 这是在方法和类上创建和使用自定义属性的正确方法吗?

c# - 自定义属性的反射或正则表达式

jQuery - 循环遍历具有特定属性的元素

c# - 是否可以将委托(delegate)作为属性参数?