.NET类型推断:无法推断"T GetValue <T>(T defaultValue = default(T))"的用法?

Sch*_*999 3 .net c# generics

我有一个简单的方法:

public static T GetValue<T>(SqlDataReader reader, int columnIndex, T defaultValue = default(T))
{
    return reader.IsDBNull(columnIndex) ? defaultValue : (T)reader[columnIndex];
}       
Run Code Online (Sandbox Code Playgroud)

和它的用法:

string s = SqlUtils.GetValue<string>(reader, nameOrd);
Run Code Online (Sandbox Code Playgroud)

我问自己,为什么我必须指定<string>是否从使用中清楚地看到返回参数的类型是字符串?但显然我必须因为否则编译器抱怨The type arguments cannot be inferred from the usage....我的逻辑在哪里失败了?

Dar*_*rov 9

我的逻辑在哪里失败了?

无处.根据规范(25.6.4 Inference of Type Arguments),编译器仅使用参数进行泛型类型推断,而不是返回值(我提醒您在方法调用中省略了默认值参数,因此违反了此​​规则).因此,如果您想使用C#,那么规范只会告诉您仅使用返回类型无法进行泛型类型推断.或者只是使用其他一些允许这种情况的CLS语言.C#没有.