微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我使用反射来获取类型对象的返回值,但它的实际类型是(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" });
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐