In C# (as of 4.0) there is no such function that allows you to limit the use of attribute based on the availability of the element.
The question is why do you want to do this?
Since the attribute below
[AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = true)] sealed class MethodTestAttribute : Attribute { public MethodTestAttribute() { } }
and below class
public class MyClass { [MethodTest] private void PrivateMethod() { } [MethodTest] protected void ProtectedMethod() { } [MethodTest] public void PublicMethod() { } }
You can easily get the attributes of private methods using the following code:
var attributes = typeof(MyClass).GetMethods(). Where(m => m.IsPrivate). SelectMany(m => m.GetCustomAttributes(typeof(MethodTestAttribute), false));
source share