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

查看:163
本文介绍了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.IsVirtual 和的 MethodInfo.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天全站免登陆