在这里摆弄 https://dotnetfiddle.net/9Ex5Jp.
给定一个函数(string a, string b) F()
,您可以解构它返回的元组:
var (a, b) = F();
(string c, string d) = F();
或者你可以直接分配它:
var (a, b) e = F();
(string a, string b) f = F();
var g = F(); // One of these things is not like the others.
类解构函数的行为类似于第一种情况。给定一个类C
with Deconstructor(out string a, out string b)
:
var c = new C();
var (h, i) = c;
(string j, string k) = c;
但编译器不会使用解构函数将其隐式转换为元组:
// Cannot implicitly convert type 'C' to '(string a, string b)'
var (a, b) l = c;
显然,您可以基于解构函数机械地编写隐式转换:
public static implicit operator (string a, string b) (C c)
{
c.Deconstruct(out string a, out string b);
return (a, b);
}
尽管解构和赋值情况之间的语法在视觉上相似,但分配对元组的引用与将类解构为变量然后将它们放入新元组中不同。但是,您可以隐式转换(int x, int y)
to (double x, double y)
。值元组是一种语法糖功能,它看起来就像它所做的那样,而不用担心实现细节。
If I thought of this, the C# team thought of it, and if they chose not to add "magic" support for the implicit conversion, they had a good reason1.
是否有积极的理由为什么自动进行隐式转换是一个坏主意?
或者它是否是那些被认为价值不足以证明其成本合理的功能之一?
这是来自的代码那个小提琴 https://dotnetfiddle.net/9Ex5Jp:
public class Program
{
public static void Main()
{
(string a, string b) = F();
(string a, string b) ab = F();
Console.WriteLine($"a: {a} b: {b} ab: {ab}");
var c = new C();
(string d, string e) = c;
// Cannot implicitly convert type 'C' to '(string a, string b)'
(string a, string b) f = c;
Console.WriteLine($"d: {d} e: {e} f: {f}");
// Covariance
(object c, object d) g = F();
// Implicit conversion
(double x, double y) t = G();
}
public static (string a, string b) F()
=> ("A", "B");
public static (int x, int y) G()
=> (0, 1);
}
public class C
{
public String A = "A";
public String B = "B";
public void Deconstruct(out String a, out String b)
{
a = A;
b = B;
}
}
1 The C# team may not be smarter than everybody, but I've never lost money betting they were at least as smart as me.