簡體   English   中英

通過反射獲取頂級派生類型的名稱

[英]Get the name of the top derived type through Reflection

我有以下情況:

public class Program
{
    static void Main(string[] args)
    {
        new Child().Foo(); //will display "Parent" but I want it to display "Child"
    }
}

class Parent
{
    virtual void Foo()
    {
        var firstFrame = new StackTrace().GetFrames().First();
        var method = firstFrame.GetMethod();
        Console.WriteLine(method.DeclaringType.Fullname);
    }
}

class Child : Parent
{

}

如您所見,我希望控制台顯示“ Child”而不是“ Parent”。 或者換種說法,我想走上堆棧跟蹤,對於堆棧跟蹤的每種方法,我都想獲得“ this”對象。

我找不到為我提供“此”對象的任何屬性。

我實際上想列出裝飾器模式的所有鏈元素。

我看到此工作的唯一方法是,如果您在子類中重寫它,然后向上移動一幀(在這種情況下,它將是孩子的foo)。

public class Program
{
    static void Main(string[] args)
    {
        new Child().Foo(); //will display "Child"
    }
}

class Parent
{
    public virtual void Foo()
    {
        StackFrame frame = new StackFrame(1);
        var method = frame.GetMethod();
        Console.WriteLine(method.DeclaringType.FullName);
    }
}

class Child : Parent
{
    public override void Foo()
    {
        base.Foo();
    }
}

如果您想將其作為列表,則可以將堆棧框架部分放在一個循環中,並繼續進行下去,直到用盡foo。 例如:

class Parent
{
    public virtual void Foo()
    {
        StackTrace trace = new StackTrace();
        List<StackFrame> frames = new List<StackFrame>(trace.GetFrames());
        var thisMethod = frames[0].GetMethod().Name;
        //we don't want ourselves in the list
        frames.RemoveAt(0);
        foreach (var frame in frames)
        {
            var method = frame.GetMethod();
            //we only want foo's
            if (method.Name == thisMethod)
            {
                Console.WriteLine(method.ReflectedType.FullName);
            }
            else
            {
                // when we've run out, we can get out
                break;
            }
        }
    }
}

這段代碼怎么樣:?

Console.WriteLine(this.GetType().FullName);

代替這個

var firstFrame = new StackTrace().GetFrames().First();
var method = firstFrame.GetMethod();
Console.WriteLine(method.DeclaringType.FullName);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM