2016-03-25 9 views
0

だから、私はこのようになりますカスタム属性を持っているTargets.Method:C#のカスタム属性、戻り値の種類= && IsStatic

[AttributeUsage(System.AttributeTargets.Method, AllowMultiple = false)] 
public class MyAttribute: System.Attribute 
{ 
    private string name; 
    public double version; 

    public MyAttribute(string _name) 
    { 
     this.name = _name; 
     version = 1.0; 
    } 
} 

この属性に以下の条件を追加することは可能です:

Method.ReturnType = typeof(specificClass) 

Method.IsStatic 

また、次の条件を実装するにはどうすればよいですか?

public static void Do(Func<type> func) where func : MyAttribute //make sure Func<type> is decorated with my attribute 
{ 
    //do something with 'func' 
} 
+0

いいえ... –

答えて

1

いいえ、そうではありません。 AttributeUsageは、カスタム属性クラスの使用方法を決定します。

最初のAttributeUsage引数(ValidOn)は、AttributeTargets列挙の1つ以上の要素である必要があります。複数のターゲット・タイプは、次のように、OR演算子と一緒にリンクすることができます:AllowMultiple引数がtrueに設定されている

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] 
class NewPropertyOrFieldAttribute : Attribute { } 

場合は、その結果の属性は、このように、単一のエンティティに複数回適用することができます。

Inheritedがfalseに設定されている場合、その属性は、帰属するクラスから派生したクラスによって継承されません。例:

[AttributeUsage(AttributeTargets.Class, Inherited = false)] 
class Attr1 : Attribute { } 

[Attr1] 
class BClass { } 

// In this case Attr1 is not applied to DClass via inheritance. 
class DClass : BClass { } 

これは、コンパイル時に属性の使用を制御できるすべてのパラメータです。実行時にリフレクションを使用シナリオを検証できますが、速度が遅く、エラーが発生する可能性があります。