具有通用约束的C#重载 [英] C# overloading with generic constraints

查看:65
本文介绍了具有通用约束的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):

方法的签名由方法的名称,类型参数的数量以及每个形式参数的类型和种类(值,引用或输出)组成,在顺序从左到右. 出于这些目的,以形式参数类型出现的方法的任何类型参数都不由其名称标识,而是由其在方法的类型参数列表中的序号位置标识. 方法的签名特别不包括返回类型,可能为最右边的参数指定的params修饰符,也不包括可选的类型参数约束.

The signature of a method consists of the name of the method, the number of type parameters and the type and kind (value, reference, or output) of each of its formal parameters, considered in the order left to right. For these purposes, any type parameter of the method that occurs in the type of a formal parameter is identified not by its name, but by its ordinal position in the type argument list of the method. The signature of a method specifically does not include the return type, the params modifier that may be specified for the right-most parameter, nor the optional type parameter constraints.

(我的重点)

因此,这两种方法的签名都是有效的:

So the signature of both methods is effectively:

GetValueOrNull<T1,T2>(IDictionary<T1,T2>,T1)

并且:

方法的重载允许类,结构或接口声明多个具有相同名称的方法,只要它们的签名在该类,结构或接口内是唯一的.


可以在将来的C#版本中完成吗?

Could it be done in future releases of C#?

我对此表示怀疑,除非或直到类型推断变得更容易解决.类型推断可能已经花费大量时间,因为编译器通常必须执行暴力破解方法.考虑到当前的机器,它还必须同时考虑重载解决方案可能会非常昂贵.

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#重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆