.NET:以其静态方法确定“此类”的类型

在非静态方法中,我可以使用this.GetType()并且它将返回Type。如何通过Type静态方法获得相同的信息?当然,我不能只写,typeof(ThisTypeName)因为ThisTypeName仅在运行时才知道。谢谢!



桃花长相依
浏览 430回答 3
3回答

智慧大石

如果您要寻找与this.GetType()静态方法等效的1衬管,请尝试以下方法。Type t = MethodBase.GetCurrentMethod().DeclaringType尽管这可能比仅使用更昂贵typeof(TheTypeName)。

人到中年有点甜

还有一些其他答案尚未完全弄清,这与您只在执行时可用的类型的想法有关。如果使用派生类型执行静态成员,则在二进制文件中将省略实类型名称。因此,例如,编译以下代码:UnicodeEncoding.GetEncoding(0);现在在其上使用ildasm ...,您将看到发出如下调用:IL_0002:  call       class [mscorlib]System.Text.Encoding [mscorlib]System.Text.Encoding::GetEncoding(int32)编译器已解决对的调用Encoding.GetEncoding-没有UnicodeEncoding剩余痕迹。恐怕这会使您对“当前类型”的想法变得荒谬。

慕妹3146593

另一种解决方案是使用自引用类型//My base class//I add a type to my base class use that in the static method to check the type of the caller.public class Parent<TSelfReferenceType>{&nbsp; &nbsp; public static Type GetType()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return typeof(TSelfReferenceType);&nbsp; &nbsp; }}然后在继承它的类中,创建一个自引用类型:public class Child: Parent<Child>{}现在,Parent内部的调用类型typeof(TSelfReferenceType)将获得并返回调用者的Type,而无需实例。Child.GetType();-抢
打开App,查看更多内容
随时随地看视频慕课网APP