4

是否可以在自定义属性的类中获取装饰类的类型?例如:

[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property, AllowMultiple = false)]
public class ViewAttribute : ExportAttribute
{

    public object TargetRegion { get; set; }
    public Type ViewModel { get; set; }
    public Type Module { get; set; }

    public ViewAttribute()
        : base(typeof(UserControl))
    {
        Module = GetDecoratedClassType(); //I need this method
    }
}

在以下示例中,GetDecoratedClassType() 将返回 HomeView

[View]
HomeView MyHomeView { get; set; }
4

2 回答 2

3

您不能将它作为参数添加到构造函数中吗?

public class ViewAttribute : ExportAttribute
{    
    public object TargetRegion { get; set; }
    public Type ViewModel { get; set; }
    public Type Module { get; set; }

    public ViewAttribute(Type decoratedClassType)
        : base(typeof(UserControl))
    {
        Module = decoratedClassType
    }
}

[View(typeof(HomeView))]
HomeView MyHomeView { get; set; }

我知道它并不完全优雅,但这就足够了吗?(而且您可能应该将 Module 的设置器设为私有)

于 2010-05-20T23:28:14.700 回答
1

看到这个答案,我倾向于同意,在反思的时候,你应该有权访问该属性所应用的成员信息。

于 2010-05-20T23:49:19.060 回答