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

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

代码

  1. public class CashierOut : BaseActivity
  2. {
  3. [Description("Flag indicates whether break to execution.")]
  4. [DefaultValue(false)]
  5. [MyCustomAttribute(ParameterGroups.Extended)]
  6. public bool CancelExecution { get; set; }
  7.  
  8. [Description("Flag indicates whether allow exit before declation.")]
  9. [DefaultValue(true)]
  10. [MyCustomAttribute(ParameterGroups.Extended)]
  11. [DisplayName("Exit before declaration?")]
  12. public bool AllowExitBeforeDeclare { get; set; }
  13. }

我想做这样的事情:

  1. public class CashierOut : BaseActivity
  2. {
  3. [MyResourceCustom("CashierOut.CancelExecution")]
  4. public bool CancelExecution { get; set; }
  5.  
  6. [MyResourceCustom("CashierOut.AllowExitBeforeDeclare")]
  7. public bool AllowExitBeforeDeclare { get; set; }
  8. }
  9.  
  10. public sealed class MyResourceCustom : Attribute
  11. {
  12. public string ResourcePath { get; private set; }
  13.  
  14. public ParameterGroupAttribute(string resourcePath)
  15. {
  16. ResourcePath = resourcePath;
  17.  
  18. // Get attributes attributes value from external resource using the path.
  19. }
  20. }

解决方法

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

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

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

猜你在找的C#相关文章