Joh*_*iak 9 c# reflection static types
我想从静态方法获取派生类型.
我想做这样的事情
void foo()
{
this.getType();
}
Run Code Online (Sandbox Code Playgroud)
但在静态方法
我知道
MethodBase.GetCurrentMethod().DeclaringType
Run Code Online (Sandbox Code Playgroud)
返回基类型,但我需要派生.
dtb*_*dtb 13
假设你的意思是你有类似的东西
class MyBaseClass
{
public static void DoSomething()
{
Console.WriteLine(/* current class name */);
}
}
class MyDerivedClass : MyBaseClass
{
}
Run Code Online (Sandbox Code Playgroud)
并想要MyDerivedClass.DoSomething();打印"MyDerivedClass",那么答案是:
你的问题没有解决方案.静态方法不像实例方法那样继承.您可以参考DoSomething使用MyBaseClass.DoSomething或MyDerivedClass.DoSomething,但两者都编译为调用MyBaseClass.DoSomething.无法找出源代码中使用哪个来进行调用.
SWe*_*eko 10
我想你需要这样的场景:
void Main()
{
Base.StaticMethod(); // should return "Base"
Derived.StaticMethod(); // should return "Derived"
}
class Base
{
public static void StaticMethod()
{
Console.WriteLine(MethodBase.GetCurrentMethod().DeclaringType.Name);
}
}
class Derived: Base
{
}
Run Code Online (Sandbox Code Playgroud)
但是,此代码将返回
Base
Base
Run Code Online (Sandbox Code Playgroud)
这是因为静态方法调用在编译时被解析为对基类的调用,实际定义它,即使它是从派生类调用的.线条
Base.StaticMethod();
Derived.StaticMethod();
Run Code Online (Sandbox Code Playgroud)
生成以下IL:
IL_0001: call Base.StaticMethod
IL_0006: nop
IL_0007: call Base.StaticMethod
Run Code Online (Sandbox Code Playgroud)
总之,它无法完成.
| 归档时间: |
|
| 查看次数: |
2252 次 |
| 最近记录: |