为什么要使用 Tuple?

这篇博客探讨了在C#中如何利用Tuple来处理方法的多值返回和参数传递。通过实例展示了Tuple在存储混合类型数据和简化访问方式上的便利性,包括创建学生信息的Tuple以及在多线程环境中传递 Tuple 的方法。
摘要由CSDN通过智能技术生成
  • 如果你的方法需要返回多个值 或者 方法需要传递多个值。

  • 如果你不想为某些功能专门去定义一个类。

  • 如果你有若干个混杂元素,并且想提供对其简单的访问方式

public TupleTest()
        {
            InitializeComponent();

            //演示Tuple
            var testTuple6 = new Tuple<int, int, int, int, int, int, int,Tuple<int,int,int,int>>(11, 12, 13, 14, 15, 16, 17,new Tuple<int,int,int,int>(21,22,23,24));
            //this.RTB_test.Text=Convert.ToString(testTuple6.Rest.Item4);

            //实例一  学生信息:姓名,年龄,体重
            var studentInfo = new Tuple<string, int, int>("test",23,120);
            this.RTB_test.Text = "学生姓名:" + Convert.ToString(studentInfo.Item1) + "\n"+"学生年龄:"+ studentInfo.Item2+"\n"+"学生体重:"+studentInfo.Item3;
            //MessageBox.Show($"Student Information: Name [{studentInfo.Item1}], Age [{studentInfo.Item2}], Height [{studentInfo.Item3}]");
        }


        #region 从方法返回多个值
        static Tuple<string,int,int> GetStudentInfo(string name)
        {
            return new Tuple<string, int, int>(name,23,110);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var studentInfo = GetStudentInfo("chen");
            this.RTB_test.Text = studentInfo.Item1 + studentInfo.Item2 + studentInfo.Item3;
        }
        #endregion

        #region 用于单参数的多值传递()
        private void WriteStudentInfo(object student)
        {
            var studentInfo = student as Tuple<string, int, int>;
            this.RTB_test.Text = studentInfo.Item1 + studentInfo.Item2 + studentInfo.Item3;
        }

        #endregion

        private void button2_Click(object sender, EventArgs e)
        {
            var t = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(WriteStudentInfo));
            t.Start(new Tuple<string,int,int>("chen",34,130));
            while (t.IsAlive)
            {
                System.Threading.Thread.Sleep(50);
            }
        }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值