当前位置:编程学习 > C#/ASP.NET >>

C# 字符串转为变量名,通过字符串给变量赋值

例子一、将字符串转为变量名

       string str = "spp";
        public string spp = "very good";
        private void button1_Click(object sender, EventArgs e)
        {
          
            MessageBox.Show(this.GetType().GetField(str).GetValue(this).ToString());

 

        }

来自:http://social.microsoft.com/Forums/zh-CN/visualcshartzhchs/thread/3b7c7d4d-925b-4d72-bee0-6c39c2e2786b

例子二、通过字符串给变量赋值

       public string gisoracle = "ok";

        private void button2_Click(object sender, EventArgs e)
        {

            //通过字符串获得变量值
            MessageBox.Show(this.GetType().GetField("gisoracle").GetValue(this).ToString());
            //通过给变量赋值
            this.GetType().GetField("gisoracle").SetValue(this, "gisoracle@126.com");
            //新的值
            MessageBox.Show(this.GetType().GetField("gisoracle").GetValue(this).ToString());
        }

    
补充:软件开发 , C# ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,