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

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

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

以上是内存溢出为你收集整理的c# – 如何从对象转换为元组(ValueTuple)类型?全部内容,希望文章能够帮你解决c# – 如何从对象转换为元组(ValueTuple)类型?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1233166.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-06
下一篇2022-06-06

发表评论

登录后才能评论

评论列表(0条)

    保存