我想订阅外部类的内部事件操作的委托:
internal static event Action OnSingletonReady;
我无法编辑它所在的类。尽管该事件将来可能会公开,但我迫不及待地希望这种情况发生。
在内部操作中添加/删除代表需要什么?
我相信,当您使用
nonPublic
反映 add 方法时设置 GetAddMethod
参数将会得到预期的结果,至少在我测试它时是这样。
using System.Reflection;
Console.Title = "Subscribe to Internal Event";
var action = typeof(ReflectionTestClass)
.GetEvent(nameof(ReflectionTestClass.OnSingletonReady), BindingFlags.Static | BindingFlags.NonPublic);
var methodInfo =
action?
.GetAddMethod(nonPublic: true);
// Subscribe to the action
methodInfo?.Invoke(action, new object[] { ()=>
{
Console.WriteLine($@"[{DateTime.Now:hh\:mm\:ss\:fff}] Event received.");
} } );
Console.WriteLine($@"[{DateTime.Now:hh\:mm\:ss\:fff}]");
await Task.Delay(1000);
_ = ReflectionTestClass.Get();
Console.ReadKey();
class ReflectionTestClass
{
private ReflectionTestClass() { }
public static ReflectionTestClass Get()
{
if(_singleton is null)
{
_singleton = new ReflectionTestClass();
OnSingletonReady?.Invoke();
}
return _singleton;
}
private static ReflectionTestClass? _singleton = null;
internal static event Action? OnSingletonReady;
}