[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; }
}
我希望限制开发人员一次只使用每个派生属性中的一个。编译器应该在这个阶段给出编译错误。我怎样才能做到这一点?有可能吗?
发布于 2016-11-21 15:33:18
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而不是枚举
https://stackoverflow.com/questions/40723238
复制相似问题