本文介绍了使用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);

推荐答案

来自解构(C#7.0)文档:

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

None of the parameters can be type arguments.

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

09-25 20:30