使用解构元组赋值扩展方法进行类型推断
Type Inference with Deconstruct tuple assignment extension methods
给出一些扩展方法:
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 :
None 个参数可以是类型参数。
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.
给出一些扩展方法:
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 :
None 个参数可以是类型参数。
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.