【问题标题】:Setting an attribute property to the type of the decorated class将属性属性设置为装饰类的类型
【发布时间】:2010-05-20 23:18:23
【问题描述】:

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

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

【问题讨论】:

    标签: c# custom-attributes


    【解决方案1】:

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

    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 的 setter 设为私有)

    【讨论】:

    • 仍然可以通过反射访问私有 setter。为了避免这种情况,您可以将 Module 设置为带有 readonly 支持字段的“仅限吸气剂”属性...
    【解决方案2】:

    看到这个answer,我倾向于同意,在反思的时候,你应该可以访问应用属性的成员信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-20
      • 2023-03-17
      • 1970-01-01
      • 2021-05-17
      • 1970-01-01
      • 2013-07-16
      • 2019-08-19
      • 1970-01-01
      相关资源
      最近更新 更多