클래스의 멤버/속성을 런타임에 동적으로 만들고 설정할 수있는 방법은 무엇입니까?런타임에 클래스의 멤버/속성을 동적으로 만들고 설정합니다.
심판 : 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"
}
}
그리고 또 다른 문제의 구성원/속성을 초기화하고 정의하는 코드는 내가 모두 원하는 것입니다 위의 초기화 후에 속성을 설정하여 하드 코딩 된 클래스 객체처럼 액세스 할 수 있습니다. 현재 코드는 마지막 속성, 즉 데이터 집합의 마지막 행의 값만 반환합니다.
을 당신이 ExpandoObject를 사용하지 않는 이유는 무엇입니까? – MikeSW
이렇게하면 어떻게 나중에이 속성에 액세스 할 수 있습니까? 그런 다음 * KeyName *을 알아야합니다. 그러나 이미 알고 있다면 사전을 사용하는 것이 어떻습니까? –
모든 값은 문자열입니까? – Ben