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());
        }

例子二、通過字符串給變量賦值

 

  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());
        }

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM