2016-11-21 6 views
1
[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; } 
} 

一度に各派生属性の1つだけを使用するように開発者を制限したいと考えています。コンパイラはこの段階でコンパイルエラーを出さなければなりません。どうすればこれを達成できますか?出来ますか?あなたの目的は、単にいくつか列挙型を定義する代わりに、いくつかの使用のためのクラスにいくつかのユニークな指標を追加する場合複数の使用のために子属性を制限する

+0

のSystem.Typeをを使用していた場合は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; } } 

のプロパティとして追加知っている、それは可能ではないttributes。 'AllowMultiple = false'は特定のAttributeクラスに対してのみ定義されているので、' Foo'属性を複数使用することはできませんが、完全な継承ツリーには使用できません。 –

答えて

1

偽AllowMultiple =が派生同じ属性タイプにのみ影響しないように見える\兄弟は、クラス

属性派生クラスとあなたの意図がfooやバーのクラスを取り、文字列の上にそれをアクティブ、限り私として代わりに列挙

+0

あなたの視点を実装しました。ありがとうございました! – Hasan

関連する問題