简体   繁体   中英

C# Method Attribute force requirements such as abstract or static?

This may be more of a design question then a "Can I do this?" question. I'm creating an attribute which its target is defined as Method. Is there any possible way to impose restrictions on the domain of methods,ie that the target method must be declared abstract, virtual, static, etc?

The ultimate goal is to scan for these methods and implement them in a subclass--however I'd like them to be abstract. Is there a better way to accomplish this psuedo-restriction on targets of my attribute?

You should be able to filter out non-virtual methods which are decorated with your attribute using MethodInfo.IsVirtual and MethodInfo.IsAbstract to get determine if it is abstract.

foreach(var assem in AppDomain.CurrentDomain.GetAssemblies())
    foreach (var type in assem.GetTypes())
        foreach (var mthdInfo in type.GetMethods())
        {
            if (mthdInfo.GetCustomAttributes(typeof(MyCustomAttribute), false) && mthdInfo.IsVirtual && !mthdInfo.IsFinal)
                // This is a method you can use
        }

There are ways to detect the other constraints you listed as well and the approach should be similar.

EDIT: Fixed to answer the question for methods.

Nope, sorry. You can play around with the Inherited argument in AttributeUsage though, it may help you somewhat.

Edit: I know this post doesn't address your question directly, but you may be able to apply some of the principals it discusses:

Restrict custom attribute so that it can be applied only to Specifc types in C#?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM