确定一个类型是静态的 [英] Determine if a type is static
问题描述
让我们说我有一个键入
名为键入
。
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):
如果键入
是 System.Windows.Point
然后我可以做到这一点:
If type
is System.Windows.Point
then I could do this:
Point point1 = new Point();
但是,如果键入
是统环境
那么这不会飞:
Environment environment1 = new Environment(); //wrong
所以,如果我通过每一个可见的类型在装配迭代我怎么跳过所有,将无法创建像第二个实例的类型?我要反思的一种新的,所以我没有很大的术语呢。但愿我想要做的,是pretty的清晰。
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.
推荐答案
静态
类中声明摘要
和密封
在IL水平。所以,你可以检查 IsAbstract
属性来处理这两个摘要
类和静态
类一气呵成(对于你的使用情况)。
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).
不过,摘要
类不是唯一的类型,你不能直接实例化。您应该检查之类的接口(没有伴生类
属性)和类型没有通过调用code访问的构造函数。
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屋!