Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/291.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何从泛型函数中检索值类型值?_C# - Fatal编程技术网

C# 如何从泛型函数中检索值类型值?

C# 如何从泛型函数中检索值类型值?,c#,C#,我有一个通用函数,用于从sqlite数据库检索键值对值 函数签名为: T Retrieve<T>(string key); T检索(字符串键); 每当数据库中不存在密钥时,我想返回null。我可以使用此签名对引用类型执行此操作,但不能使用值类型 我可以将签名更改为对象检索(字符串键)然后将其转换为typeT,但我想知道是否还有其他更好的方法来实现这一点。这里有一些竞争因素: 常规值类型不能为null Nullable可以是null,但那将是T?Retrieve(字符串键),其中

我有一个通用函数,用于从sqlite数据库检索键值对值

函数签名为:

T Retrieve<T>(string key);
T检索(字符串键);
每当数据库中不存在密钥时,我想返回
null
。我可以使用此签名对
引用类型
执行此操作,但不能使用
值类型


我可以将签名更改为
对象检索(字符串键)
然后将其转换为type
T
,但我想知道是否还有其他更好的方法来实现这一点。

这里有一些竞争因素:

  • 常规值类型不能为
    null
  • Nullable
    可以是
    null
    ,但那将是
    T?Retrieve(字符串键),其中T:struct
    ,这将使您无法使用
    Retrieve(…)
    ,这似乎是一个可能的用例
所以,;你不能同时拥有这两个。您希望单独考虑报告结果值及其是否为代码> null <代码>,例如,其中一个:

bool TryRetrieve<T>(string key, out T value);
T Retrieve<T>(string key, out bool isNull);
(T value, bool isNull) Retrieve<T>(string key);
其中as
out
参数不适用于大多数
async
场景

async Task<(T value, bool isNull)> RetrieveAsync<T>(string key);