c# - 使用解构元组赋值扩展方法进行类型推断

标签 c# tuples extension-methods type-inference

给定一些扩展方法:

public static TO ConvertValue<TI, TO>(TI value) => (TO)Convert.ChangeType(value, typeof(TO));

public static void Deconstruct<TI, TO1, TO2>(this IEnumerable<TI> src, out TO1 p1, out TO2 p2) {
    var e = src.GetEnumerator();
    p1 = e.MoveNext() ? ConvertValue<TI,TO1>(e.Current) : default(TO1);
    p2 = e.MoveNext() ? ConvertValue<TI,TO2>(e.Current) : default(TO2);
}

为什么 C# 编译器无法在此处为 Deconstruct 推断类型:

(double p1, int p2) = new int[] {  1, 2, 3, 4 };

但是在这里推断类型没有问题吗?

Ext.Deconstruct(new int[] {  1, 2, 3 }, out int p3, out double p4);

最佳答案

来自 deconstructions (C# 7.0) documentation :

所有参数都不能是类型参数。

The resolution is equivalent to typing rhs.Deconstruct(out var x1, out var x2, ...); with the appropriate number of parameters to deconstruct into. It is based on normal overload resolution. This implies that rhs cannot be dynamic and that none of the parameters of the Deconstruct method can be type arguments. A Deconstruct(out T x1, out T x2) method will not be found.

关于c# - 使用解构元组赋值扩展方法进行类型推断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46840305/

相关文章:

c++ - 用另一个元组中的元素填充一个元组

.net - 为什么我需要这个。在母版页中使用扩展方法的限定符?

c# - 在 C# 中从 DataGrid 导出到 Excel 时停止日期自动格式化

c# - 拉动刷新 UWP - GridView ?

c++ - 为参数包中的每种类型推导模板参数类型

python - 元组列表转为 CSV

c# - .NET 3.5 及更低版本中内联的替代方案

c# - 有没有办法将 CSS 类动态分配给 MVC4 Html.Encode 条目?

.net - 扩展方法是将函数添加到枚举的唯一方法吗?

C# 向量类 - 插值设计决策