【问题标题】:Is it possible to determine the type responsible for constructing an attribute in c#是否可以确定负责在 c# 中构造属性的类型
【发布时间】:2013-05-23 21:38:37
【问题描述】:

在用属性修饰的类型上调用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 的调用者

【问题讨论】:

  • stackoverflow.com/questions/1235617/… 可以将类型传递给属性构造函数
  • 没有好的方法。你也许可以用堆栈跟踪/帧做一些事情,但没有什么漂亮
  • @cheedep 我试图避免传入类型,因为在一个类型上可能有很多这样的情况,它看起来过于多余。
  • @MarcGravell 谢谢,我就是这么想的。
  • 你可以用 postsharp 来做(见stackoverflow.com/questions/7851365/…),但它使用一些编译时魔法在幕后做同样的事情。

标签: c# .net reflection attributes


【解决方案1】:

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

[AttributeUsage(AttributeTargets.Class)]
class MyAttribute : Attribute
{
    public Type CallingType { get; set; }

    public MyAttribute(Type type)
    {
       // heres your magic
       this.CallingType = type;
    }
}

用法:

[MyAttribute(typeof(MyClass))]

【讨论】:

  • 投反对票是有道理的,因为显然有更好的方法来做到这一点:/sarcasm
猜你喜欢
  • 2014-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-09
  • 2013-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多