Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I was wondering if it's possible (even via reflection et similia) to get the caller derived-class inside of a called base-class static method.

For example, I've a base-class with a static method defined:

public MyBaseClass {
    public static void MyBaseClassStaticMethod() { /** ... **/ }
}

and a derived-from-it class:

public MyDerivedClass : MyBaseClass { }

then I call:

MyDerivedClass.MyBaseClassStaticMethod()

Is it possibile, inside of method MyBaseClassStaticMethod, to know which is the caller derived type?
(i.e. MyDerivedClass)

I just need a string...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
273 views
Welcome To Ask or Share your Answers For Others

1 Answer

Generics in following way can be used to solve your scenario

public class BaseClass<TDerived> where TDerived : BaseClass<TDerived>
{
    public static void LogCallerType()
    {
        Console.WriteLine(typeof(TDerived).Name);
    }
}

public class FooClass : BaseClass<FooClass> { }

public class BooClass : BaseClass<BooClass> { }

class Program
{
    static void Main(string[] args)
    {
        FooClass.LogCallerType();
        BooClass.LogCallerType();
    }
}

This will in turn output the following

1. FooClass
2. BooClass

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...