获取课程类型?

时间:2010-10-10 01:45:45

标签: c# reflection .net-4.0

鉴于

public class A
{
    public static void Foo()
    {
        // get typeof(B)
    }
}

public class B : A
{

}

{4}可以在.NET 4中获得B.Foo()吗?请注意,typeof(B)是静态的。

2 个答案:

答案 0 :(得分:4)

A.Foo()B.Foo()之间没有区别。在两种情况下,编译器都会调用A.Foo()。所以,不,没有办法检测FooA.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>();
    }
}