简体   繁体   English

使用Deconstruct元组赋值扩展方法键入推理

[英]Type Inference with Deconstruct tuple assignment extension methods

Given some 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);
}

Why is it that the C# compiler is unable to infer the types for Deconstruct here: 为什么C#编译器无法在此处推断Deconstruct的类型:

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

But has no problem inferring the types here? 但是在这里推断类型没有问题吗?

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

From deconstructions (C# 7.0) documentation : 解构(C#7.0)文档

None of the parameters can be type arguments. 这些参数都不是类型参数。

The resolution is equivalent to typing rhs.Deconstruct(out var x1, out var x2, ...); 分辨率相当于输入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. 这意味着rhs不能是动态的,并且Deconstruct方法的任何参数都不能是类型参数。 A Deconstruct(out T x1, out T x2) method will not be found. 将找不到解构(out t x1,out T x2)方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM