[C/C#]以字串的值 作為變數名稱取得變數值

如題,一個很抽象的概念。
任何程式語言中所謂的變數,都只在coding時有效而已
在真正編譯後會全部轉為組合語言,程式執行的時候才不管變數是什麼
只靠位置在作用。

所以根據結構(struct/class)的大小以及記憶體的位移值去動態取得想要的變數是有可能實現的
在C#中可以輕易做到

但在C語言裡面目前我還沒有成功,只有大概的方向及概念。

參考:
C
程式設計俱樂部
C#
MSDN - 宣告
MSDN - 設值
Google_E-Book - 取得方式



以下我寫了一個父類別


public class ClassBase
    {        public virtual string[] Property()
        {
            List<string> ListVariableAll = new List<string>();
            foreach (PropertyInfo n in this.GetType().GetProperties())
                if (n.Name != "Item" && n.Name != "Property")
                    ListVariableAll.Add(n.Name);

            return ListVariableAll.ToArray();
        }

        public virtual object GetData()
        { return this; }

        [JsonIgnore]
        public virtual object this[string key]
        {
            set
            {
                Type t = this.GetType();
                PropertyInfo pro = t.GetProperty(key);
                if (pro != null)
                    pro.SetValue(this, value, null);
                else
                    throw new Exception("參數:[" + key + "]不存在");
            }
            get
            {
                Type t = this.GetType();
                PropertyInfo pro = t.GetProperty(key);

                if (pro != null)
                    return pro.GetValue(this, null) == null ? "" : pro.GetValue(this, null).ToString();
                else
                    return null;
            }
        }
    }

使用時,直接將你所寫的類別 繼承此類別
然後宣告變數都可直接宣告成ClassBase

因為它是原始類別,雖然不包含子類別的元素,但是基本元素如上面所宣告的都會存在
藉此我們可以利用Type的變數取得整個類別的model,然後從我們給予的key值中用GetValue函數取得值,反之也可以利用SetValue給予值

範例專案

以上。

沒有留言:

張貼留言