我想获得与Action委托相关联的对象,并确定其是否为空。我该怎么做呢?没有反思,这可能吗?
Action
是一个委托类型,因此它的基类是从Delegate
继承的MulticastDelegate
,它暴露了Method和Target
属性。您可能对Target
感兴趣,因为它"获取当前委托调用实例方法的类实例"。它的值是"当前委托调用实例方法的对象,如果委托代表一个实例方法;如果委托代表静态方法,则为Null。"
如果您将Action
对象强制转换为MulticastDelegate
(或Delegate
),您可以像以下代码片段一样验证:
public class A
{
public void foo()
{
Console.WriteLine("A.foo()");
}
public void foo2()
{
Console.WriteLine("A.foo2()");
}
public static void bar()
{
Console.WriteLine("A.bar()");
}
}
class Program
{
static void Main(string[] args)
{
A a = new A();
Action action = a.foo;
action += a.foo2;
MulticastDelegate d = (MulticastDelegate)action;
Debug.Assert(object.ReferenceEquals(d.Target, a)); // passes
action();
action = A.bar;
d = (MulticastDelegate)action;
Debug.Assert(object.ReferenceEquals(d.Target, null)); // passes
action();
}
}
输出:A.foo()
A.foo2()
A.bar()
注意,Target
返回最后一个添加到调用列表的对象的实例:
public class B
{
public void foo()
{
Console.WriteLine("B.foo()");
}
}
class Program
{
static void Main(string[] args)
{
A a = new A();
B b = new B();
Action action = a.foo;
action += a.foo2;
action += b.foo;
MulticastDelegate d = (MulticastDelegate)action;
Debug.Assert(object.ReferenceEquals(d.Target, b)); // passes
action();
action = A.bar;
d = (MulticastDelegate)action;
Debug.Assert(object.ReferenceEquals(d.Target, null)); // passes
action();
}
}
输出:A.foo()
A.foo2()
B.foo()
A.bar()