简体   繁体   English

使用反射来获取静态类的列表

[英]Use reflection to get a list of static classes

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. 如何在C#3.5中使用反射来获取程序集中的所有静态类。 I already get all Types defined, but there is no IsStatic property. 我已经定义了所有类型,但没有IsStatic属性。 Counting 0 constructors is really slow and did not work either. 计数0构造函数非常慢,也无法正常工作。

Any tips or a line of code? 任何提示或一行代码? :-) :-)

Chris 克里斯

Here is how you get types from an assembly: 以下是从汇编中获取类型的方法:

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

GetTypes Method GetTypes方法

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 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. 在博客中搜索我可以找到.NET CLR不知道静态类的想法的信息,但是允许同时使用抽象和密封类型标志。 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. CLR还使用这些标志来优化其行为,例如,使用密封标志调用密封类的虚拟方法,如非虚拟方法。 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);

What C# calls a static class, is an abstract, sealed class to the CLR. C#调用静态类是CLR的一个抽象密封类。 So you'd need to look at IsAbstract && IsSealed. 所以你需要看看IsAbstract && IsSealed。

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. 静态类是C#的一个特性,而不是公共语言规范,因此Type实例上没有任何一个元数据可以表明它是一个静态类。 You can, however, check to see if it's a sealed type, and if all of its non-inherited members are static. 但是,您可以检查它是否为密封类型,以及是否所有非继承成员都是静态的。

You need to combine following checks: Abstract, Sealed, BeforeFieldInit. 您需要结合以下检查:Abstract,Sealed,BeforeFieldInit。 After static class compiles you can see following IL code in the compiled assembly: 在静态类编译之后,您可以在编译的程序集中看到以下IL代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM