如何在C#中使用字串來取得同名的變數值

如何在C#中使用字串來取得同名的變數值

using System;

namespace Test
{
	class MainClass
	{
		public int myInteger = 7;
		
		public void Test()
		{
                       // Grabs the integer by the variables name
			int test = (int)this.GetType().GetField("myInteger").GetValue(this);
			
			Console.WriteLine(test);
		}
		
		public static void Main(string[] args)
		{
			MainClass mc = new MainClass();
			
			mc.Test();
		}
	}
}

發表迴響

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 變更 )

Twitter picture

You are commenting using your Twitter account. Log Out / 變更 )

Facebook照片

You are commenting using your Facebook account. Log Out / 變更 )

Google+ photo

You are commenting using your Google+ account. Log Out / 變更 )

連結到 %s