开发者

Get class type?

Given

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

public class B : A
{

}

Is it pos开发者_运维知识库sible for B.Foo() to get typeof(B) in .NET 4? Note that Foo is static.


There is no difference between A.Foo() and B.Foo(). The compiler emits a call to A.Foo() in both cases. So, no, there is no way to detect if Foo was called as A.Foo() or B.Foo().


Unfortunately this isn't possible, as dtb explains.

One alternative is to make A generic like so:

public class A<T>
{
    public static void Foo()
    {
        // use typeof(T)
    }
}

public class B : A<B>
{
}

Another possibility is to make the A.Foo method generic and then provide stub methods in the derived types that then call the "base" iplementation.

I'm not keen on this pattern. It's probably only worthwhile if you absolutely need to keep the B.Foo calling convention, you can't make A itself generic, and you have lots of shared logic inside A.Foo that you don't want to repeat in your derived types.

public class A
{
    protected static void Foo<T>()
    {
        // use typeof(T)
    }
}

public class B : A
{
    public static void Foo()
    {
        A.Foo<B>();
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜