确定类型是否为静态 [英] Determine if a type is static

查看:26
本文介绍了确定类型是否为静态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个名为 typeType.

Let's say I have a Type called type.

我想确定是否可以对我的类型执行此操作(而不对每种类型实际执行此操作):

I want to determine if I can do this with my type (without actually doing this to each type):

如果 typeSystem.Windows.Point 那么我可以这样做:

If type is System.Windows.Point then I could do this:

Point point1 = new Point();

但是如果 typeSystem.Environment 那么这不会飞:

However if type is System.Environment then this will not fly:

Environment environment1 = new Environment(); //wrong

因此,如果我遍历程序集中的每个可见类型,我该如何跳过所有无法创建类似第二个实例的类型?我对反射有点陌生,所以我对术语还不是很熟悉.希望我在这里要做的事情很清楚.

So if I am iterating through every visible type in an assembly how do I skip all the types that will fail to create an instance like the second one? I'm kind of new to reflection so I'm not that great with the terminology yet. Hopefully what I'm trying to do here is pretty clear.

推荐答案

static 类在 IL 级别被声明为 abstractsealed.因此,您可以检查 IsAbstract 属性以一次性处理 abstract 类和 static 类(针对您的用例).

static classes are declared abstract and sealed at the IL level. So, you can check IsAbstract property to handle both abstract classes and static classes in one go (for your use case).

然而,abstract 类并不是您不能直接实例化的唯一类型.你应该检查接口之类的东西(没有CoClass 属性) 和没有调用代码可访问的构造函数的类型.

However, abstract classes are not the only types you can't instantiate directly. You should check for things like interfaces (without the CoClass attribute) and types that don't have a constructor accessible by the calling code.

这篇关于确定类型是否为静态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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