开发者

Setting an attribute property to the type of the decorated class

开发者 https://www.devze.com 2023-01-01 01:08 出处:网络
Is it possible to get the decorated class\' type inside of the custom attribute\'s class? For example:

Is it possible to get the decorated class' type inside of the custom attribute's class? For example:

[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 = Get开发者_运维技巧DecoratedClassType(); //I need this method
    }
}

In the following example GetDecoratedClassType() would return HomeView

[View]
HomeView MyHomeView { get; set; }


Couldn't you add it as an argument in the constructor?

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

I know it's not exactly elegant, but would that suffice? (And you should probably make the setter for Module private)


See this answer, i tend to agree, at the point of reflection you should have access to the member info that the attribute is applied to.

0

精彩评论

暂无评论...
验证码 换一张
取 消