我正在测试Reflection上的Console应用程序来调用其访问修饰符是私有的委托.
代码如下所示:
public class EventPublisher
{
private delegate void PrivateDelegate(string message);
public delegate void PublicDelegate(string message);
}
public class PrivateDelegateSubscriber
{
public void Subscribe(EventPublisher evPub)
{
Type t = typeof(EventPublisher);
MemberInfo[] privateDelegate = t.GetMember("PrivateDelegate", BindingFlags.NonPublic);
Delegate delByReflection = Delegate.CreateDelegate((System.Type)privateDelegate.GetValue(0), this, "MethodForPrivateDelegate");
// how to call the private delegate like public delegate below?
Delegate delByReflection2 = Delegate.CreateDelegate(typeof(EventPublisher.PublicDelegate), this, "MethodForPrivateDelegate");
EventPublisher.PublicDelegate delByReflection2_ins = (EventPublisher.PublicDelegate)delByReflection2;
delByReflection2_ins("test public delegate");
}
public void MethodForPrivateDelegate(string message)
{
Console.WriteLine("This is from private delegate subscriber, writing: " + message);
}
}
我已经测试了公共代表,它正在按预期工作,但我没有找到任何方法在私人代表上执行此操作.我的问题是上面的注释代码,如果有任何方法可以做到,或者为什么不可能.
提前致谢
最佳答案
how to cast to private delegate like public delegate below?
你没有.强制转换是一个编译时声明,需要访问相关类型.声明变量具有您尝试声明变量的代码无法访问的类型是不可能的.
但是,您仍然可以使用DynamicInvoke()方法调用此类委托.例如.:
delByReflection.DynamicInvoke("test private delegate");