关于Delegate中的Target属性的理解

在看MvvmLights框架中的WeakAction源码的时候,才了解到Delegate中有Target这么一个属性

MSDN的解释是这样的 Gets the class instance on which the current delegate invokes the instance method.

获取当前委托调用的实例方法的实例。有点拗口哈。

写下实例代码验证一下,顺便加深下印象。

// 定义一个Action属性,给他赋值后,查看下Target是什么东西
public partial class MainWindow : Window
{
    public Action TestAction { get; set; }
    private void Button_Click_2(object sender, RoutedEventArgs e)
    {
        Test a = new Test();
        TestAction = a.TestAction;
        RemindBox.Success(TestAction.Target.GetType().FullName);
    }
    public void TestMethod()
    {

    }
}


// 测试类
public class Test
{
    public static void StaticTestAction()
    {
    }
    public void TestAction()
    {
    }
}
  1. 赋值为Test类的TestAction, Target的类型为typeof(Test)
  2. 赋值为Test类的StaticTestAction, Target为null
  3. 赋值为MainWindow类的TestMethod, Target的类型为typeof(MainWindow)
  4. 另外的,当使用lambda表达式赋值时,输出为所在类型加上匿名类,例如MainWindow+<>c

最后总结一下:Target属性对应的值为,委托所执行的方法所在的实例,如果是静态方法,则为null

posted @ 2021-08-27 14:24  yaoqinglin_mtiter  阅读(229)  评论(0编辑  收藏  举报