首页 > 解决方案 > 如何从对象转换为元组(ValueTuple)类型?

问题描述

我使用反射来获取类型的返回值object,但它的实际类型是(int[], string[])我仔细检查obj.GetType().ToString()并打印出来System.ValueTuple`2[System.Int32[],System.String[]]的。

但只是强制转换((int[], string[]))obj(ValueTuple<int[],string[]>)obj返回该强制转换无效。如何正确地做到这一点?

标签: c#

解决方案


好的,我终于让它工作了。

可以进一步体现出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" });
    }
}

推荐阅读