Get a class?

Considering

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

public class B : A
{

}

Is it possible to B.Foo()get typeof(B)in .NET 4? Please note that Foois static.

+3
source share
2 answers

Unfortunately, this is not possible, as dtb explains .

One option is to make Ageneric as follows:

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

public class B : A<B>
{
}

Another possibility is to make the method A.Foogeneral, and then provide stub methods in derived types, which then invoke the "basic" ialmentation.

. , , 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>();
    }
}
+3

A.Foo() B.Foo(). A.Foo() . , , , Foo A.Foo() B.Foo().

+4

Source: https://habr.com/ru/post/1768808/


All Articles