2013-12-16 26 views
5

如何在運行時動態創建和設置類的成員/屬性。在運行時動態創建和設置類的成員/屬性

編號:http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.trygetmember(v=vs.110).aspx

我試圖修改的理念,以滿足我的要求,但無法做到這一點。

我需要在運行時設置類成員,意味着我會從數據庫讀取的KeyValue和我的課將與運行前定義沒有成員完全動態的,但在運行時所有的人都被取出從數據庫。

所以在這裏不用我的代碼(從MSDN獲取):

public class DynamicObjDictionary : DynamicObject 
{ 
    // The inner dictionary. 
    Dictionary<string, object> dictionary = new Dictionary<string, object>(); 
    public int Count 
    { 
     get{return dictionary.Count;} 
    } 

public override bool TryGetMember(GetMemberBinder binder, out object result) 
    { 
     string name = binder.Name.ToLower(); 
     return dynDict.TryGetValue(name, out result); 
    } 

    public override bool TrySetMember(SetMemberBinder binder, object value) 
    { 
     dynDict[binder.Name.ToLower()] = value; 
     return true; 
    } 
} 
} 

初始化和定義類

dynamic DynObj = new DynamicObjDictionary(); 
     DataSet ds = new DataSet(); 
     ds = GetObjectProperties() // returns dataset having the properties as key and value pair; 
     if (ds.Tables["PropTable"].Rows.Count > 0) 
     { 
      foreach (DataRow dr in ds.Tables["PropTable"].Rows) 
      { 
       string KeyName = dr["KeyName"].ToString(); 
       string ValueName= dr["ValueName"].ToString(); 
       //---I want that in place of fldName the actual value from dr is added to the class - currently it returns DynObj.KeyName only. 
       DynObj.KeyName = ValueName; 
       // Means if current dr["KeyName"].ToString() has "Property1" 
       // And dr["ValueName"].ToString() has "PropertyValue" 
       // The DynObj should be like DynObj.Property1 = "PropertyValue" 
      } 
     } 

而另一個問題的成員/屬性的代碼是我希望所有在上述初始化之後要設置的屬性,以便我可以像硬編碼的類對象那樣訪問它們。當前代碼僅銷售最後一個屬性,即數據集最後一行的值。

+0

? – MikeSW

+0

如果你這樣做,你以後如何訪問這些屬性?然後,您需要知道* KeyName *,但是如果您已經知道它,爲什麼不使用字典? –

+0

你所有的值都是字符串? – Ben

回答

7

要麼添加一個基於字典的API,要麼使用已有的實現。坦率地說你爲什麼不使用ExpandoObject ExpandoObject將做工精細,並具有IDictionary<string,object> API內置的。

var obj = new ExpandoObject(); 
DataSet ds = GetObjectProperties() // returns dataset having the properties as key and value pair; 
if (ds.Tables["PropTable"].Rows.Count > 0) 
{ 
    foreach (DataRow dr in ds.Tables["PropTable"].Rows) 
    { 
     string KeyName = dr["KeyName"].ToString(); 
     string ValueName= dr["ValueName"].ToString(); 
     obj[KeyName] = ValueName; 
    } 
} 
dynamic DynObj = obj; 
// ... 
+0

謝謝你的答案和上面的建議。我不得不實際使用'ExpandoObject()'來維護'Key-Value'對,然後將數據作爲動態返回。 – Cyberpks

+0

@marc:我試過你的代碼,但是這行給出錯誤obj [KeyName] = ValueName;我正在使用VS2010。任何幫助。 – Thomas

+1

@Thomas啊,這完全有可能是我在'手機上寫的!您可能需要將'obj'強制轉換爲'IDictionary '來訪問索引器 –

相關問題