约束系统.类型的类型安全参数



我有一个字典 - 其键是 System.Type。我不进一步限制字典条目;但是,字典仅通过公共类界面暴露。我正在模仿事件系统。

System.Collections.Generic Dictionary看起来像:

private Dictionary<Type, HashSet<Func<T>>> _eventResponseMap;

公开字典的方法之一具有以下签名:

public bool RegisterEventResponse<T>(Type eventType, Func<T> function)

但是,我不希望类用户能够通过此签名将任何System.Type添加到字典中。有什么方法可以进一步限制Type参数?

我真正想要的是类似于(伪代码)的东西:

public bool RegisterEventResponse<T>(Type eventType, Func<T> function) where Type : ICustomEventType

不,您将无法在Type上获得编译时间安全。

您可以约束T(或将参数添加到ICustomEventType),然后在RegisterEventResponse中使用typeof来获取您要寻找的Type对象。

或者只是抛出例外:

if (!typeof(ICustomEventType).IsAssignableFrom(typeof(T))
{
    throw new ArgumentException("Type is not supported");
}

为什么不更改方法的签名?

public bool RegisterEventResponse<TEvent, TReturn>(Func<TReturn> function)
    where TEvent: ICustomEventType
{
    _eventResponseMap[typeof(TEvent)] = function;  
}

是的,您会失去类型推理,但您会获得类型的安全性。而不是编写RegisterEventResponse(typeof(CustomEvent), () => 1),您需要编写RegisterEventResponse<CustomEvent, int>(() => 1)

相关内容