开发者

How to tell if a Type is a static class? [duplicate]

This question already has answers here: Closed 10 years ago.

Possible Duplicate:

Determine if a type is static

Duplicate of Determine if a type is static

Is there a property/attribute I can inspect to see if a System.Type is a static class?

I开发者_高级运维 can do this indirectly, by testing that the Type has static methods, and no instance methods beyond those inherited from System.Object, however it doesn't feel clean (I've a sneaking suspicion I'm missing something and this isn't a rigorous enough definition of static class).

Is there something I'm missing on the type that will categorically tell me this is a static class?

Or is static class c# syntax sugar and there's no way to express it in IL?

Thanks

BW


yea, you need to test for both IsAbstract and IsSealed. A non static class can never be both. Not fantastic but it works.


At IL level any static class is abstract and sealed. So you can do something like this:

    Type myType = typeof(Form1);
    if (myType.GetConstructor(Type.EmptyTypes) == null && myType.IsAbstract && myType.IsSealed)
    {
        // class is static
    }


        if (typeof(C).Attributes.HasFlag(System.Reflection.TypeAttributes.Abstract) &&
             typeof(C).Attributes.HasFlag(System.Reflection.TypeAttributes.Sealed) && 
            typeof(C).Attributes.HasFlag(System.Reflection.TypeAttributes.Class) )
            {
            }

but may be there is a class with this attributes but it's not static

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜