![](/img/trans.png)
[英]Can you use reflection to find out the type of the object on which the current method is executing?
[英]Find out on which type a static method was called
我有一个带有静态方法的类A
和一个派生类B
您可以在A
和B
上调用A
声明的Foo()
:
public class A
{
public static void Foo()
{
// How to get typeof(B) here if Foo called by using class B?
}
}
public class B : A
{
}
...
static class Program
{
static void Main()
{
B.Foo();
}
}
现在在Foo()
内部,如何找出调用了哪种Foo()
类型?
我不能使用关键字this
,因为我在这里没有创建任何对象。 我已经尝试过了:
MethodBase.GetCurrentMethod().DeclaringType
和
MethodBase.GetCurrentMethod().ReflectedType
但是它们都返回typeof(A)
给我,而我需要得到typeof(B)
。
我不确定您要实现的目标是什么,并不确定是否可以采用不同的方法。 这样说,您可以使用泛型基类做您需要做的事情吗?
public class AB<T>
{
public static void Foo()
{
Console.WriteLine(typeof(T));
}
}
public class A : AB<A> { }
public class B : AB<B> { }
A.Foo(); // A
B.Foo(); // B
在这种情况下,无法在静态方法Foo()中获取typeof(B)。 可能的解决方案是在Foo方法中使用参数。
感谢@Jon Skeet和@CodeCaster。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.