Use reflection to get a list of static classes

2019-04-28 04:28发布

many questions are close, but none answers my problem...

How do I use reflection in C# 3.5 to get all classes which are static from an assembly. I already get all Types defined, but there is no IsStatic property. Counting 0 constructors is really slow and did not work either.

Any tips or a line of code? :-)

Chris

4条回答
戒情不戒烟
2楼-- · 2019-04-28 04:42

Here is how you get types from an assembly:

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

GetTypes Method

Then:

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

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

Searching in blogs I could find the information that .NET CLR does not know the idea of static classes, however allows using the abstract and sealed type flags simultaneously. These flags are also used by the CLR to optimize its behavior, for example the sealed flag is used call virtual methods of sealed class like non-virtuals. So, to ask if a 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);
查看更多
姐就是有狂的资本
3楼-- · 2019-04-28 04:42

Static classes are a feature of C#, not the Common Language Specification, and so there's no one piece of metadata on a Type instance that would indicate that it's a static class. You can, however, check to see if it's a sealed type, and if all of its non-inherited members are static.

查看更多
▲ chillily
4楼-- · 2019-04-28 04:43

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

查看更多
孤傲高冷的网名
5楼-- · 2019-04-28 04:46

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

.class public abstract auto ansi sealed beforefieldinit StaticClass
    extends [mscorlib]System.Object
{
}
查看更多
登录 后发表回答