Limiting attribute use only to public and protected C # variables

Is it possible to limit the use of an attribute to protected and public variables only. I just want to restrict private variables.

+4
source share
3 answers

No, you cannot do this. You can restrict the use of attributes only by type of purpose, and not differently.

[AttributeUsage(AttributeTargets.Method)] public class MethodOnlyAttribute : Attribute { } 
+7
source

You can do this using PostSharp , here is an example of a field that can only be applied to a public or protected field:

 [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; } } 
+5
source

As far as I know, you cannot. The AttributeTargets enumeration lists which application elements you can restrict the use of attributes.

+4
source

All Articles