【发布时间】:2014-04-29 08:21:20
【问题描述】:
为什么这两个方法不能同名?是因为 C# 编译器在重载时没有考虑泛型类型约束吗?可以在未来的 C# 版本中实现吗?
public static TValue GetValueOrNull<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key)
where TValue : class
{
TValue value;
if (dictionary.TryGetValue(key, out value))
return value;
return null;
}
public static TValue? GetValueOrNull<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key)
where TValue : struct
{
TValue value;
if (dictionary.TryGetValue(key, out value))
return value;
return null;
}
【问题讨论】:
-
这里的名称不同。看不出有什么问题。你得到什么错误?
-
他自己改的名字,应该是TValue GetValueOrNull和TValue? GetValueOrNull.
-
@Uriel_SVK:这不是重复的 - OP 希望通用约束将成为签名的一部分,但事实并非如此。