【问题标题】:Restrict child attributes for multiple usage限制子属性以供多次使用
【发布时间】:2017-04-05 00:42:02
【问题描述】:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public abstract class AttBase : Attribute 
{
public static string Apply(object obj);
}    
public class FooAttribute : AttBase {}
public class BarAttribute : AttBase {}

public class MyClass
{
    [Foo]
    [Bar]
    public string MyProperty { get; set; }
}

我想限制开发人员一次只能使用每个派生属性中的一个。编译器在这个阶段应该给出编译错误。我怎样才能做到这一点?有可能吗?

【问题讨论】:

  • 据我所知,属性是不可能的。 AllowMultiple = false只是为具体的Attribute类定义的,所以不能使用多个Foo-Attributes,而不是完整的继承树。

标签: c# .net oop inheritance attributes


【解决方案1】:

AllowMultiple = false 似乎只影响相同的属性类型而不是派生的\兄弟属性类

如果您的目的是为类添加一些独特的指示符以用于某些用途,只需定义一些枚举而不是派生类并将其添加为 AttBase 的属性

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class AttBase : Attribute 
{
   public IndicatorType Indicator {get;set;}
   public AttBase(IndicatorType indicator )
   {
      Indicator = indicator;
   }
}

public enum IndicatorType 
{
  Foo,
  Bar,
}

public class MyClass
{
    [AttBase(IndicatorType.Foo)]
    public string MyProperty { get; set; }
}

如果您打算使用 Foo 或 Bar 类并在字符串上激活它,请使用 System.Type 而不是枚举

【讨论】:

  • 我们实现了您的观点。谢谢!
猜你喜欢
  • 2018-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-10
  • 2012-05-10
  • 2016-09-23
相关资源
最近更新 更多