鉴于
public class A
{
public static void Foo()
{
// get typeof(B)
}
}
public class B : A
{
}
{4}可以在.NET 4中获得B.Foo()
吗?请注意,typeof(B)
是静态的。
答案 0 :(得分:4)
A.Foo()
和B.Foo()
之间没有区别。在两种情况下,编译器都会调用A.Foo()
。所以,不,没有办法检测Foo
是A.Foo()
还是B.Foo()
。
答案 1 :(得分:3)
不幸的是,这是不可能的,as dtb explains。
另一种方法是使A
通用如下:
public class A<T>
{
public static void Foo()
{
// use typeof(T)
}
}
public class B : A<B>
{
}
另一种可能性是使A.Foo
方法通用,然后在派生类型中提供存根方法,然后调用“基础”实现。
我并不热衷于这种模式。如果你绝对需要保持B.Foo
调用约定,你不能使A
本身是通用的,并且你在A.Foo
内有很多你没有的共享逻辑,这可能是值得的。想要在派生类型中重复。
public class A
{
protected static void Foo<T>()
{
// use typeof(T)
}
}
public class B : A
{
public static void Foo()
{
A.Foo<B>();
}
}