C#属性:统治它们的一个属性?

前端之家收集整理的这篇文章主要介绍了C#属性:统治它们的一个属性?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
是否可以在属性上分配属性并使用它来分配其他属性 – 这样做而不使用反射?

代码

public class CashierOut : BaseActivity
{
    [Description("Flag indicates whether break to execution.")]
    [DefaultValue(false)]
    [MyCustomAttribute(ParameterGroups.Extended)]
    public bool CancelExecution { get; set; }

    [Description("Flag indicates whether allow exit before declation.")]
    [DefaultValue(true)]
    [MyCustomAttribute(ParameterGroups.Extended)]
    [DisplayName("Exit before declaration?")]
    public bool AllowExitBeforeDeclare { get; set; }
}

我想做这样的事情:

public class CashierOut : BaseActivity
{
    [MyResourceCustom("CashierOut.CancelExecution")]
    public bool CancelExecution { get; set; }

    [MyResourceCustom("CashierOut.AllowExitBeforeDeclare")]
    public bool AllowExitBeforeDeclare { get; set; }
}

public sealed class MyResourceCustom : Attribute
{
    public string ResourcePath { get; private set; }

    public ParameterGroupAttribute(string resourcePath)
    {
        ResourcePath = resourcePath;

        // Get attributes attributes value from external resource using the path.
    }
}

解决方法

属性只是将元数据添加到他们定义的成员 – 他们自己什么都不做.

您必须使用反射才能根据属性值产生一些行为.

这就是所有属性的工作原理 – 一些工具知道某些属性(如编译器和ConditionalAttribute),但这仍然是通过反射完成的.

猜你在找的C#相关文章