3

我有一个简单的方法:

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

及其用法:

string s = SqlUtils.GetValue<string>(reader, nameOrd);

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

4

1 回答 1

9

我的逻辑在哪里失败?

无处。根据规范25.6.4 Inference of Type Arguments(因此,如果您想使用 C#,规范只是告诉您泛型类型推断仅使用返回类型是不可能的。或者简单地使用其他一些允许这样做的 CLS 语言。C# 没有。

于 2012-07-16T22:03:02.167 回答