我需要调用以下函数:
当我使用字符串数组(引用类型)调用GetValueOrDefault时,它可以正常工作:
当我使用int(ValueType)数组调用GetValueOrDefault时,它不起作用:
编译器错误为:
我知道我可以使用泛型来解决这个问题,但我想了解这个错误。
static string GetValueOrDefault(object[] values, int index)
{
if (values == null)
return string.Empty;
if (index >= values.Length)
return string.Empty;
return values[index] != null ? values[index].ToString() : string.Empty;
}
当我使用字符串数组(引用类型)调用GetValueOrDefault时,它可以正常工作:
GetValueOrDefault(new[] {"foo", "bar"}, 0);
当我使用int(ValueType)数组调用GetValueOrDefault时,它不起作用:
GetValueOrDefault(new[] {1, 2}, 0);
编译器错误为:
所以我的问题是:为什么这不像引用类型和值类型都派生自object一样编译?MyNamespace.GetValueOrDefault(object[], int)的最佳重载方法匹配具有一些无效参数
我知道我可以使用泛型来解决这个问题,但我想了解这个错误。
static string GetValueOrDefault<T>(T[] values, int index)
{...}
提前感谢