Use reflection to get a list of static classes.

many questions are close, but no one answers my problem ...

How to use reflection in C # 3.5 to get all classes static from assembly. I have already defined all types, but there is no IsStatic property. Counting 0 constructors is very slow and doesn't work.

Any hints or line of code? :-)

Chris

+6
reflection c # static
source share
4 answers

Here's how you get types from an assembly:

http://msdn.microsoft.com/en-us/library/system.reflection.assembly.aspx

GetTypes Method

Then:

Look for classes that are abstract and sealed at the same time.

http://dotneteers.net/blogs/divedeeper/archive/2008/08/04/QueryingStaticClasses.aspx

Searching for blogs I could find information that the .NET CLR does not know the idea of ​​static classes, however, it allows the use of abstract and private type flags at the same time. These flags are also used by the CLR to optimize its behavior, for example, a sealed flag is used to call virtual methods of a closed class, such as non-virtual. So, to ask if the type is static or not, you can use this method:

From the comment below:

IEnumerable<Type> types = typeof(Foo).Assembly.GetTypes().Where (t => t.IsClass && t.IsSealed && t.IsAbstract); 
+12
source share

What C # calls a static class is an abstract, private class for the CLR. So you need to look at IsAbstract && IsSealed.

+3
source share

Static classes are a C # function, not a Common Language Specification, and therefore there is not a single piece of Type instance metadata that indicates that it is a static class. However, you can check if it is a private type, and if all its non-inherited members are static.

+1
source share

You need to combine the following checks: Annotation, Sealed, BeforeFieldInit. After static class compilation, you can see the following IL code in the compiled assembly:

 .class public abstract auto ansi sealed beforefieldinit StaticClass extends [mscorlib]System.Object { } 
+1
source share

All Articles