给定一些扩展方法:
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/