Hi
Is it possible to restrict an attribute usage to just protected and public variables. I just want to restrict to private variables.
Hi
Is it possible to restrict an attribute usage to just protected and public variables. I just want to restrict to private variables.
No, you can't do that. You can restrict attribute usage only based on the type of the target, not anything else.
[AttributeUsage(AttributeTargets.Method)]
public class MethodOnlyAttribute : Attribute {
}
To the best of my knowledge, you cannot. The AttributeTargets enumeration lists which application elements you can constrain attribute usage to.
You can do this with PostSharp, here's an example of a field which 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;
}
}