Nic*_*ron 5 c# generics asynchronous nullable method-signature
我有这个代码:
public async static Task<T?> RequestValue1<T>(Command requestCommand)
where T : struct
{
// Whatever
}
public async static Task<T> RequestValue2<T>(Command requestCommand)
where T : class
{
// Whatever
}
Run Code Online (Sandbox Code Playgroud)
我希望我的两种方法具有相同的名称.这甚至可能吗?
我的问题:
Nullable<T>if T是值类型,Tif 的实例T是引用类型.async不允许ref/out,因此如果没有类型的方法参数T,T则不推断并且我的两个方法不能具有相同的名称(签名冲突,因为如果T不推断,泛型约束不适用于签名冲突解决)目前这段代码有效,但我不喜欢"RequestValue1"和"RequestValue2"之间的这种奇怪的函数调用.
您可以创建自己的Option类型并使用它来指示是否返回值:
public async static Task<Option<T>> RequestValue<T>(Command requestCommand) {
...
}
Run Code Online (Sandbox Code Playgroud)
更新:该类型的目的Option<T>是替换nulls 和Nullable<T>s,但如果您仍然想使用它们,可以使用这些扩展方法来弥补差距:
public static class OptionExtensions {
public static T? GetNullableValue<T>(this Option<T> option) where T : struct {
return option.HasValue ? (T?)option.Value : null;
}
public static T GetValueOrNull<T>(this Option<T> option) where T : class {
return option.HasValue ? option.Value : null;
}
}
Run Code Online (Sandbox Code Playgroud)