我们可以使用Delegate对象跟踪委托调用链吗? [英] can we Trace delegate Call chain by using Delegate object ?

查看:63
本文介绍了我们可以使用Delegate对象跟踪委托调用链吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 MethodA(委托obj)
{
MethodB(obj):
}

MethodB(委托obj)
{
MethodC(obj):
}


MethodC(委托obj)
{
// 使用obj需要跟踪所有Travellled方法信息

// 类似MethodA.MethodB.MethodC
}

解决方案

方法的参数参数是私有变量只存在于Method的范围内...除非你使用'ref或'out ...但我不认为在运行时有任何实用的方法,即使使用'out /'ref,也可以找出给定对象访问的位置,因为它可以从一个方法传递给另一个方法。



我能想到的最接近的事情就是在多播事件代表的运行时使用反射...你没有r在其调用列表中对代理的引用...获取其调用列表并枚举其委托。以下是这样做的示例:[ ^ ]。



假设您想在类中使用非静态元素,您可以执行以下操作:

  public   class 历史记录
{
public 静态列表< string> MethodHistory = new List< string>();

public static void 报告()
{
foreach var str MethodHistory)Console.WriteLine(str);
}
}

私有 void act0( )
{
历史记录= 历史记录();
History.MethodHistory.Add( act0);
act1( ref 历史记录);
}

private void act1( ref 历史记录历史记录)
{
History.MethodHistory.Add( ACT1);
act2( ref 历史记录);
}

private void act2( ref 历史记录历史记录)
{
History.MethodHistory.Add( ACT2);
act3( ref 历史记录);
}

private void act3( ref 历史记录历史记录)
{
History.MethodHistory.Add( ACT3);
History.Report();
}
< / string > < / string > ;


MethodA(Delegate obj)
{
  MethodB(obj):
}

MethodB(Delegate obj)
{
  MethodC(obj):
}


MethodC(Delegate obj)
{
  //By using obj need to Track all The Travellled Methods info

  // Like MethodA.MethodB.MethodC
}

解决方案

Parameter arguments to a Method are private variables existing only in the scope of the Method ... unless you use 'ref or 'out ... but I don't think there's any practical way at run-time, even using 'out/'ref, to find out where a given object has "visited" as it may be passed from method to method.

The closest thing I can think of to what you may be after is using reflection at run-time on a multi-cast Event delegate ... where you do not have references to the delegates in its invocation list ... to get its invocation list and enumerate its delegates. Here's an example of doing that: [^].

Assuming you wanted to use non-static elements in a Class, you could do something like this:

public class History
{
    public static List<string> MethodHistory = new List<string>();

    public static void Report()
    {
        foreach (var str in MethodHistory) Console.WriteLine(str);
    }
}

private void act0()
{
    History history = new History();
    History.MethodHistory.Add("act0");
    act1(ref history);
}

private void act1(ref History history)
{
    History.MethodHistory.Add("act1");
    act2(ref history);
}

private void act2(ref History history)
{
    History.MethodHistory.Add("act2");
    act3(ref history);
}

private void act3(ref History history)
{
    History.MethodHistory.Add("act3");
    History.Report();
}
</string></string>


这篇关于我们可以使用Delegate对象跟踪委托调用链吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆