是否有可能确定c#中负责构造属性的类型?

本文关键字:属性 类型 有可能 是否 | 更新日期: 2023-09-27 18:15:00

属性构造函数在使用属性装饰的类型上调用GetCustomAttributes()之后被调用。是否可以从构造函数中确定调用类型。我想做一些类似于下面的事情,让它不抛出。

class Program
{
    static void Main(string[] args)
    {
        var myAttributedClassType = typeof(MyAttributedClass);
        var customAttributes = myAttributedClassType.GetCustomAttributes(false)
                                                    .OfType<MyAttribute>();
        if (customAttributes.Any(x => x.CallingType != myAttributedClassType))
        {
            throw new Exception("MyAttribute.CallingType was incorrect.");
        }
    }
}
[AttributeUsage(AttributeTargets.Class)]
class MyAttribute : Attribute
{
    public Type CallingType { get; set; }
    public MyAttribute()
    {
        // magic to set CallingType goes here
    }
}
[MyAttribute]
class MyAttributedClass { }

更新:

我知道这可以通过构造函数 中的命名参数轻松实现。
[MyAttribute(CallingType = typeof(MyAttributedClass)

或必需的参数

public MyAttributed(Type callingType)
{
    CallingType = callingType;    // this doesn't qualify as magic ;)
}

,但希望有一种方法来避免它,因为类型对象本身(我想要的值)是GetCustomAttributes

是否有可能确定c#中负责构造属性的类型?

的调用者

你的魔法,虽然不是真正的魔法:

[AttributeUsage(AttributeTargets.Class)]
class MyAttribute : Attribute
{
    public Type CallingType { get; set; }
    public MyAttribute(Type type)
    {
       // heres your magic
       this.CallingType = type;
    }
}

用法:

[MyAttribute(typeof(MyClass))]