加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何从对象转换为元组(ValueTuple)类型?

发布时间:2020-12-15 22:51:58 所属栏目:百科 来源:网络整理
导读:我使用反射来获取类型对象的返回值,但它的实际类型是(int [],string [])我用obj.GetType()进行双重检查.ToString()并打印System.ValueTuple`2 [ System.Int32 [],System.String []]. 但只是使用((int [],string []))obj或(ValueTuple int [],string [])obj进
我使用反射来获取类型对象的返回值,但它的实际类型是(int [],string [])我用obj.GetType()进行双重检查.ToString()并打印System.ValueTuple`2 [ System.Int32 [],System.String []].

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

解决方法

好的,我终于搞定了.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读