如何创建命名引用类型元组?

以下行创建一个命名的ValueTuple

 var tuple = (a:1, b:2, c:3, d:4, e:5, f:6); 

值类型无法有效传递。 C#7是否提供了一种创建元Tuple类型的命名元组的方法?

如果你的意思是有办法将其他名称附加到System.Tuple<...>实例的属性,那么没有。

根据您的需要,您可以通过使用ToValueTuple中的ToValueTuple重载将System.Tuple<...>实例转换为System.ValueTuple<...>实例并使用ToValueTuple重载返回来实现ToTuple

如果你真的不需要元组,可以使用Deconstruct重载或var (v1, .., vn) = tuple解构语法将它们解构为离散变量。

不确定是什么问题; 一切都按照预期的方式传递新的ValueTupleoutref和新的ref本地

我正在使用.NET 4.7并在.csproj设置“高级…”按钮中将我的C#7编译器设置为“最新”。

演示function:

 static (int, int) g = (1, 2); static void SetValues(int a, int b, ref (int, int) tt) => tt = (a, b); static void SetValuesOut(int a, int b, out (int, int) tt) => tt = (a, b); static ref (int, int) GetKnownTuple() => ref g; static ref (int, int) SelectRef( int ix, ref (int, int) x, ref (int, int) y, ref (int, int) z) { if (ix == 0) return ref x; if (ix == 1) return ref y; return ref z; } 

用法示例:

 /// use 'ref return' to initialize a new 'ref local' tuple 'aa' ref (int, int) aa = ref GetKnownTuple(); /// or use the same function without 'ref' to create a local COPY 'bb' var bb = GetKnownTuple(); /// use 'ref' parameter to modify values of local copy 'bb' ('aa/g' are not altered) SetValues(3, 4, ref bb); /// deconstruction of 'ref local' tuple; reads values from referent 'g' (1, 2) (int x, int y) = aa; /// 'ref local' reference to a local tuple copy ref (int, int) dd = ref bb; /// use 'out' parameter to construct a new (non-'ref') local tuple 'cc' SetValuesOut(y, x, out (int, int) cc); /// ...or use 'out' with 'ref local' to wholly replace existing referent ('g' here) SetValuesOut(5, 6, out aa); /// 'ref return' function can also be used as assignment l-value... GetKnownTuple() = (7, 8); /// ('aa/g' are altered; locals 'bb' and 'cc' remain unchanged) /// ...or assign a referent via 'ref local' variable (changes 'g' again) aa = (9, 10); /// conditional assignment via 'ref return' (changes 'g' again) SelectRef(0, ref aa, ref bb, ref cc) = (11, 12); 

应该清楚的是,更多的是可能的,但由于OP的问题没有涉及太多具体的进一步要求,因此无法在此显示所有内容。