Cyb*_*pks 5 c# oop class dynamic
如何在运行时动态创建和设置类的成员/属性.
参考: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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
初始化和定义类的成员/属性的代码
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"
}
}
Run Code Online (Sandbox Code Playgroud)
另一个问题是我希望在上面的初始化之后设置所有属性,以便我可以像硬编码的类对象一样访问它们.当前代码仅零售最后一个属性,即数据集的最后一行的值.
添加基于字典的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;
// ...
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
10524 次 |
最近记录: |