c# - 如何从对象转换为元组(ValueTuple)类型?
问题描述
我使用反射来获取类型的返回值object
,但它的实际类型是(int[], string[])
我仔细检查obj.GetType().ToString()
并打印出来System.ValueTuple`2[System.Int32[],System.String[]]
的。
但只是强制转换((int[], string[]))obj
或(ValueTuple<int[],string[]>)obj
返回该强制转换无效。如何正确地做到这一点?
解决方案
好的,我终于让它工作了。
可以进一步体现出ValueTuple
's Field ItemX
。不确定是否还有其他不那么强制的方法可以让我们获得整个元组。
using System;
namespace CTest
{
class Program
{
static void Main(string[] args)
{
Test t = new Test();
var tuple = typeof(Test).GetMethod(nameof(t.ReturnTuple)).Invoke(t, null);
int[] i = (int[])typeof((int[], string[])).GetField("Item1").GetValue(tuple);
string[] s = (string[])typeof((int[], string[])).GetField("Item2").GetValue(tuple);
foreach (int data in i)
{
Console.WriteLine(data.ToString());
}
foreach (string data in s)
{
Console.WriteLine(data);
}
// Output :
// 1
// 2
// 3
// a
// b
// c
}
}
class Test
{
public (int[], string[]) ReturnTuple() => (new int[] { 1, 2, 3 }, new string[] { "a", "b", "c" });
}
}
推荐阅读
- kotlin - 如何在外部(ini)函数中初始化不可变类成员
- javascript - 使用猫鼬时如何不通过函数传递值
- amazon-web-services - AWS Beanstalk 驱动器已满?
- java - 使用 Docker 打包 Maven
- r - 有没有办法计算ecdf的面积?
- javascript - 使用 user_id 的 javascript 对象过滤器不返回预期结果
- angular - Angular 8:使 FormBuilder 仅接受带有纬度和经度范围的数字
- c# - 无法在 .NET Core 3.0 中使用 AssemblyLoadContext 加载插件依赖项
- python - Pygame精灵不会出现
- python - 画一条连接悬垂(脊)的线