[英]Bind properties of a class at runtime (Create ViewModel at runtime)
[英]Dynamically create and set members/properties of class at runtime
如何在運行時動態創建和設置類的成員/屬性。
參考: http : //msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.trygetmember( v= vs.110).aspx
我試圖修改這個想法以滿足我的要求,但無法做到。
我需要在運行時設置類成員,這意味着我將從數據庫中獲取Key
和Value
,並且我的類將是完全動態的,在運行時之前沒有成員定義,但所有這些都是在運行時從數據庫中獲取的。
所以這里是我的代碼(取自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"
}
}
另一個問題是我希望在上面的初始化之后設置所有屬性,以便我可以像硬編碼的類對象一樣訪問它們。 當前代碼僅零售最后一個屬性,即數據集的最后一行的值。
添加基於字典的API,或使用已有它的實現。 坦率地說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;
// ...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.