限制公共和受保护变量的属性用法c#

4 c# attributes

是否可以将属性使用限制为仅受保护和公共变量.我只想限制私有变量.

Meh*_*ari 8

不,你做不到.您可以仅根据目标的类型限制属性使用,而不是其他任何内容.

[AttributeUsage(AttributeTargets.Method)]
public class MethodOnlyAttribute : Attribute { 
}
Run Code Online (Sandbox Code Playgroud)


the*_*onk 5

您可以使用PostSharp执行此操作,这是一个只能应用于公共或受保护字段的字段示例:

[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;
    }
}
Run Code Online (Sandbox Code Playgroud)