调用基类静态方法时获取Caller派生类 [英] Get Caller derived-class when calling a base-class static method
问题描述
我想知道是否有可能(甚至通过反射等)将调用者的派生类获取到称为基类的静态方法中。
I was wondering if it's possible (even via reflection et similia) to get the caller derived-class inside of a called base-class static method.
,我有一个定义了静态方法的基类:
For example, I've a base-class with a static method defined:
public MyBaseClass {
public static void MyBaseClassStaticMethod() { /** ... **/ }
}
以及派生的- from-it类:
and a derived-from-it class:
public MyDerivedClass : MyBaseClass { }
然后我打电话:
MyDerivedClass.MyBaseClassStaticMethod()
是否可以在方法 MyBaseClassStaticMethod
内使用是呼叫者派生类型?
(即 MyDerivedClass
)
Is it possibile, inside of method MyBaseClassStaticMethod
, to know which is the caller derived type?
(i.e. MyDerivedClass
)
我只需要一个字符串...
I just need a string...
推荐答案
不,这是不可能的-绝不是。 静态
方法不是多态的,因此这些信息根本不存在。
考虑重新设计代码。
No, this is not possible - by no means. static
methods are not polymorphal and as such this information simply doesn't exist.
Consider redesigning your code.
更新:
编译后,编译器将 MyDerivedClass
替换为静态方法是实际上在您的情况下声明为 MyBaseClass
。
因此,即使在IL中,您也看不到 MyDerivedClass
。该信息在源代码中仅存在 。它在您的已编译程序集中不存在。
Upon compilation, the compiler replaces MyDerivedClass
with the class the static method is actually declared on, in your case MyBaseClass
.
So even in the IL you don't see MyDerivedClass
. The information exists only in your source code. It doesn't exist in your compiled assembly.
这篇关于调用基类静态方法时获取Caller派生类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!