C# 方法属性强制要求如抽象或静态? [英] C# Method Attribute force requirements such as abstract or static?

查看:33
本文介绍了C# 方法属性强制要求如抽象或静态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能更像是一个设计问题,而不是我可以这样做吗?"题.我正在创建一个属性,其目标被定义为方法.有没有办法对方法域施加限制,即目标方法必须声明为抽象、虚拟、静态等?

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,i.e 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?

推荐答案

您应该能够使用 MethodInfo.IsVirtualMethodInfo.IsAbstract 以确定它是否是抽象的.

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.

已修复以回答方法问题.

Fixed to answer the question for methods.

这篇关于C# 方法属性强制要求如抽象或静态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆