本文介绍了具有通用约束的C#重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 为什么这两个方法不能具有相同的名称?是否因为C#编译器不考虑泛型类型约束进行重载?可以在将来的C#版本中完成吗?Why those two methods cannot have the same name? Is it because C# compiler does not take the generic type constraints into consideration for overloading? Could it be done in future releases of 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;}推荐答案绝对正确.请参见 C#语言规范(版本5):(我的重点)因此,这两种方法的签名都是有效的:So the signature of both methods is effectively:GetValueOrNull<T1,T2>(IDictionary<T1,T2>,T1)并且:我对此表示怀疑,除非或直到类型推断变得更容易解决.类型推断可能已经花费大量时间,因为编译器通常必须执行暴力破解方法.考虑到当前的机器,它还必须同时考虑重载解决方案可能会非常昂贵.I doubt it, unless or until type inference becomes an easier problem to solve. Type inference can already take large amounts of time because the compiler usually has to perform a brute-force approach. It having to also consider overload resolution at the same time may be prohibitively expensive given current machines. 这篇关于具有通用约束的C#重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
09-17 07:34