泛型,可空,类型推断和函数签名冲突

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)

我希望我的两种方法具有相同的名称.这甚至可能吗?

我的问题:

  • 由于返回类型,我必须编写两种不同的方法(如果请求失败,我希望它为null;如果请求成功,我希望它为值),Nullable<T>if T是值类型,Tif 的实例T是引用类型.
  • async不允许ref/out,因此如果没有类型的方法参数T,T则不推断并且我的两个方法不能具有相同的名称(签名冲突,因为如果T不推断,泛型约束不适用于签名冲突解决)

目前这段代码有效,但我不喜欢"RequestValue1"和"RequestValue2"之间的这种奇怪的函数调用.

Jor*_*dão 4

您可以创建自己的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)