【问题标题】:How to cast from object to tuple (ValueTuple) type?如何从对象转换为元组(ValueTuple)类型?
【发布时间】:2018-06-24 22:51:34
【问题描述】:

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

但只是使用((int[], string[]))obj(ValueTuple<int[],string[]>)obj 进行转换会返回转换无效。如何正确做到这一点?

【问题讨论】:

  • 第一次转换需要一组额外的括号:((int[], string[]))obj
  • 啊,是的,对不起,这就是我正在做的事情,它返回演员表无效。
  • 您的项目是否针对不支持元组的旧 C# 语言版本?
  • 为什么需要做这种事情?也许解释你想要达到的目标可以引导你找到正确的解决方案。
  • 我的意思是尝试: ((int[], string[]))obj.Value 。如果这不起作用,请尝试 GetType、GetProperty、GetValue,如 Heinzi 在这里的回答:stackoverflow.com/questions/8631546/…

标签: c#


【解决方案1】:

好吧,我终于搞定了。

可以进一步反映ValueTuple的字段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" });
    }
}

【讨论】:

    猜你喜欢
    • 2021-11-04
    • 2023-03-19
    • 2019-07-12
    • 1970-01-01
    • 2013-01-14
    • 2021-09-09
    • 2020-12-28
    • 2021-06-04
    • 1970-01-01
    相关资源
    最近更新 更多