Mat*_*vey 6 c# tuples syntactic-sugar
我希望在C#中看到的是关于元组的更好的语法,例如.
var rgb = (1.0f, 1.0f, 1.0f);
// Inferred to be Tuple<float, float, float>
// Translated to var rgb = Tuple.Create(1.0f, 1.0f, 1.0f)
Run Code Online (Sandbox Code Playgroud)
和
var x, y, z = rgb;
// Translated to:
// float x = rgb.Item1;
// float y = rgb.Item2;
// float z = rgb.Item3;
Run Code Online (Sandbox Code Playgroud)
C#语言中有什么禁止这个,或者实现它太难/不现实吗?也许还有其他语言功能会与此直接冲突?
请注意,我不是在询问这是否在微软雷达上,或者即使它与他们对C#的愿景保持一致,只是理论上它有明显的阻挡剂.
编辑 以下是其他CLI语言的一些示例
// Nemerle - will use a tuple type from a language specific runtime library
def colour = (0.5f, 0.5f, 1.0f);
def (r, g, b) = colour;
// F# - Will use either a library type or `System.Tuple` depending on the framework version.
let colour = (0.5f, 0.5f, 1.0f)
let (r, g, b) = colour
// Boo - uses CLI array
def colour = (0.5, 0.5, 1.0)
def r, g, b = colour
// Cobra - uses CLI array
var colour = (0.5, 0.5, 1.0)
var r, g, b = colour
Run Code Online (Sandbox Code Playgroud)
虽然使用数组似乎是一个很好的折衷方案,但在混合类型时它变得有限.let a, b = (1, "one")F#或Nemerle会给我们一个Tuple<int, string>.在Boo或Cobra这会给我们一个object[].
Edit2 语言支持在C#7中添加 - https://www.kenneth-truyers.net/2016/01/20/new-features-in-c-sharp-7/
Tigran 和 Hilgarth 已证明第二种语法不可行。
让我们看第一个语法:
var rgb = (1.0f, 1.0f, 1.0f);
Run Code Online (Sandbox Code Playgroud)
如果您不想使用该类Tuple,因为您想使用该类MyTuple(这可能具有IEnumerable<object>非常有用的优点!),会发生什么?显然该语法没有帮助。你必须把MyTuple课程放在某个地方......
MyTuple<float, float, float> rgb = (1.0f, 1.0f, 1.0f);
Run Code Online (Sandbox Code Playgroud)
或者
var rgb = new MyTuple<float, float, float>(1.0f, 1.0f, 1.0f);
Run Code Online (Sandbox Code Playgroud)
现在,这种新的速记语法的优势不再存在,因为您必须将MyTuple<float, float, float>.
请注意,没有任何单个集合初始值设定项可以简单地“自动发现”所有内容。
var myVar = new List<int> { 1, 2, 3 };
Run Code Online (Sandbox Code Playgroud)
在这里,我们谈论 a 的事实List<int>非常清楚:-)
即使是有点“特殊”的数组初始值设定项也不是隐式的......
int[] myVar = { 1, 2, 3 };
var myVar = new[] { 1, 2, 3 };
var myVar = new int[] { 1, 2, 3 };
Run Code Online (Sandbox Code Playgroud)
都是有效的,但我们谈论数组的事实总是明确的(总是有一个[])
var myVar = { 1, 2, 3 };
Run Code Online (Sandbox Code Playgroud)
无效:-) 并且数组具有作为原始构造的“优势”(数组由 IL 语言直接支持,而所有其他集合都构建在其他 .NET 库和/或数组之上)