Jon*_*ood 5 c# generics null dictionary nullable
我正在尝试使用泛型编写以下方法.(我的实际方法比这更复杂.)
public T ParseDictionaryItem<T>(string s, Dictionary<string, T> dictionary)
{
T result;
if (dictionary.TryGetValue(s, out result))
return result;
// TODO: Return special value such as null to indicate invalid item
}
Run Code Online (Sandbox Code Playgroud)
我的目标是返回类似null物品不在字典中的东西.
问题是我不知道是什么类型T.T例如,如果是整数,那么我应该返回类型T?.但是,如果T是一个类,那么它已经可以为空了.直到运行时我才会知道这一点.
任何人都可以看到一个干净的方法来返回此方法中的特殊值,以指示该项无效?我愿意回归其他东西null,但它必须是一个特殊的价值.(0不是整数的特殊值.)
Jon*_*eet 11
我建议返回一个ParseResult<T>,其定义如下:
public struct ParseResult<T>
{
// Or an exception, or a way of creating an exception
private readonly bool success;
private readonly T value;
// Accessors etc
}
Run Code Online (Sandbox Code Playgroud)
这样你就不必担心可空性了,你可以非常清楚你正在做什么.这是我在Noda Time中使用的模式,在我看来它运作得很好.(目前我们使用的是类而不是结构,但我可能会更改...)
我更喜欢其他方法,因为:
out参数不同,调用很干净Tnull 是一次成功的解析值也许两个重载会有所帮助:
public T? ParseStructDictionaryItem<T>(string s, Dictionary<string, T> dictionary) where T : struct
{
T result;
if (dictionary.TryGetValue(s, out result))
return result;
return null;
}
public T ParseReferenceDictionaryItem<T>(string s, Dictionary<string, T> dictionary) where T : class
{
T result;
if (dictionary.TryGetValue(s, out result))
return result;
return default(T);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
315 次 |
| 最近记录: |