2009-07-08 7 views

Répondre

7

Non, vous ne pouvez pas faire cela. Vous pouvez limiter l'utilisation des attributs uniquement en fonction du type de la cible, et rien d'autre.

[AttributeUsage(AttributeTargets.Method)] 
public class MethodOnlyAttribute : Attribute { 
} 
4

Au meilleur de ma connaissance, vous ne pouvez pas. L'énumération AttributeTargets répertorie les éléments d'application auxquels vous pouvez restreindre l'utilisation des attributs.

5

Vous pouvez le faire avec PostSharp, voici un exemple d'un champ qui ne peut être appliquée à un domaine public ou protégé:

[Serializable] 
[AttributeUsage(AttributeTargets.Field)] 
public class MyAttribute : OnFieldAccessAspect 
{ 
    public override bool CompileTimeValidate(System.Reflection.FieldInfo field) 
    { 
     if (field.IsPublic || field.IsFamily) 
     { 
      throw new Exception("Attribute can only be applied to Public or Protected fields"); 
     } 

     return true; 
    } 
} 
Questions connexes