给定一个函数(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
和 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)
隐式转换为 (double x, double y)
。值元组是一种语法糖功能,它看起来就像它所做的那样,而不用管实现细节。
如果我想到这一点,C# 团队也想到了,如果他们选择不为隐式转换添加“魔法”支持,他们就有充分的理由1。
为什么自动进行隐式转换不是一个好主意有积极的理由吗?
或者它是那些值(value)不足以证明成本合理的功能之一?
这是来自 that fiddle 的代码:
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 C# 团队可能并不比每个人都聪明,但我从来没有输过赌注他们至少和我一样聪明。
最佳答案
在 C# 7 发布之前(由我提出,所以我在这里有偏见)要求能够像隐式转换器一样进行解构。团队的回应是(正如我所读到的那样)它被要求太接近 C# 7 版本并且实现起来会花费太长时间,因此没有考虑。由于它现在将是一个重大变化,所以它永远不会发生。
有关此事的实际讨论,请参阅“Allow Deconstruct and implicit operator to both support deconstruction and conversion to tuple types”roslyn repo 问题。
关于C#7 值元组/解构不对称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43920598/