我在这个类中尝试为其中一个类创建模板,为此,我需要能够传递委托类型来定义事件。我添加了委托约束,以确保它是一个委托。
public abstract class TemplateScriptEvent<DelegateType> : ScriptEvent where DelegateType : Delegate
{
public event DelegateType Event;
}
但是,这导致
Error CS0066 '_ScriptEvent<DelegateType>.Event': event must be of a delegate type
我正在尝试做的事情是否可能,为什么会失败?
我正在使用.Net Framework 4.7.2。
它不起作用,因为您不能将通用参数强制为的非抽象派生类型MulticastDelegate
,这将满足C#事件声明(换句话说,您可以用Delegate
类型本身代替约束参数)。
推荐的解决方案:
如果使用常规事件,则根本不需要使用委托约束。只需使用通用EventHandler<T>
委托并仅替换其事件参数即可:
public abstract class TemplateScriptEvent<TEventArgs> : ScriptEvent
where TEventArgs : EventArgs
{
public event EventHandler<TEventArgs> Event;
protected virtual void OnEvent(TEventArgs e) => Event?.Invoke(this, e);
}
任何委托类型的抽象“事件”:
如果您确实要使用任何委托类型,那么您可以执行的最接近的解决方案是这样的:
public abstract class TemplateScriptDelegate<TDelegate, TResult> : ScriptEvent
where TDelegate : Delegate
{
// this is a simple property rather than an event, but allows +=/-= for concrete delegate types
// (and also simple assignments).
public TDelegate Event { get; set; }
// you must implement this in a more concrete derived type
protected abstract TResult OnEvent();
}
// To be able to use this you need a derived type for each delegate types (which of course,
// can have type arguments for return value and parameters).
// For example, you can have a derived type for Func<T> delegates:
public class TemplateScriptFunc<TResult> : TemplateScriptDelegate<Func<TResult>, TResult>
{
protected override TResult OnEvent() => Event.Invoke();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句