问题描述
namespace Test
{
static class TestClass
{
static (int a,int b) test = (1,0);
static void v()
{
var a = test.a;
var b = test.b;
_ = (a,b);
}
}
} 那么有什么方法可以在 CLI/C++ 中创建一个名称不同于 Item1 和 Item2 的 ValueTuple,以便它可以在 C# 中使用。 我使用的是 .Net Framework 4.7。
解决方法
值的名称不是 ValueTuple<...>
的一部分。
名称由编译器维护,并且在需要与外部代码通信时添加属性。
在 sharplab.io 上查看。
这个:
namespace Test
{
static class TestClass
{
static (int a,int b) test = (1,0);
static void v()
{
var a = test.a;
var b = test.b;
_ = (a,b);
}
}
}
将被翻译成这样:
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security;
using System.Security.Permissions;
namespace Test
{
internal static class TestClass
{
[TupleElementNames(new string[] {
"a","b"
})]
private static ValueTuple<int,int> test = new ValueTuple<int,int>(1,0);
private static void v()
{
int item2 = test.Item1;
int item = test.Item2;
}
}
}