动态变量名的实现方法

using System;
using System.Reflection;

namespace ConsoleApplication1
{
    class Class1
    {
        int bc = 100;
        int abc = 1000;

        public int getValue(string wl)
        {
            FieldInfo fi = this.GetType().GetField("a" + wl, BindingFlags.NonPublic | BindingFlags.Instance);
            if (fi == null)
                throw (new Exception("cant   find   a" + wl));
            if (fi.FieldType != typeof(int))
                throw (new Exception("type   unmatched"));
            return (int)fi.GetValue(this);
        }

        public void Run()
        {
            string str = Console.ReadLine();
            try
            {
                Console.WriteLine(this.getValue(str));
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Class1 x = new Class1();
            while (true)
            {
                x.Run();
            }
           
        }
    }
}

你可能感兴趣的:(.net)