User Attribute — Use the attribute for individual users.

I am creating a custom attribute and I would like to set AttributeUsage (or maybe some other attribute in the attribute class) so that my attribute can only be used in private methods , maybe?

Thanks in advance for your answers!

+4
source share
1 answer

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)); 
+3
source

Source: https://habr.com/ru/post/1332919/


All Articles