【发布时间】:2023-03-16 12:49:01
【问题描述】:
这是简化的案例。我有一个存储一个委托的类,它将在完成时调用:
public class Animation
{
public delegate void AnimationEnd();
public event AnimationEnd OnEnd;
}
我有另一个实用程序类,我想订阅各种委托。在构造时,我希望自己注册到委托,但除此之外它不关心类型。问题是,我不知道如何在类型系统中表达它。这是我的伪C#
public class WaitForDelegate
{
public delegateFired = false;
// How to express the generic type here?
public WaitForDelegate<F that's a delegate>(F trigger)
{
trigger += () => { delegateFired = true; };
}
}
提前致谢!
感谢 Alberto Monteiro,我只使用 System.Action 作为事件的类型。我现在的问题是,如何将事件传递给构造函数以便它可以注册自己?这可能是一个非常愚蠢的问题。
public class Example
{
Animation animation; // assume initialized
public void example()
{
// Here I can't pass the delegate, and get an error like
// "The event can only appear on the left hand side of += or -="
WaitForDelegate waiter = new WaitForDelegate(animation.OnEnd);
}
}
【问题讨论】: