使用Deconstruct元组分配扩展方法进行类型推断 [英] Type Inference with Deconstruct tuple assignment extension methods

查看:179
本文介绍了使用Deconstruct元组分配扩展方法进行类型推断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一些扩展方法:

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的类型:

Why is it that the C# compiler is unable to infer the types for Deconstruct here:

(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);

推荐答案

来自任何一个参数都不能是类型参数.

None of the parameters can be type arguments.

分辨率等效于键入rhs.Deconstruct(out var x1,out var x2,...);带有适当数量的参数以进行解构 进入.它基于正常的过载分辨率.这意味着 不能是动态的并且解构的任何参数都不能 方法可以是类型参数.解构(输出T x1,输出T x2) 找不到方法.

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.

这篇关于使用Deconstruct元组分配扩展方法进行类型推断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆