我知道存在一些解決此問題的問題,但答案通常沿着推薦字典或參數集合的路線行事,這在我的情況下不起作用。在運行時動態添加C#屬性
我正在使用一個通過反射工作的庫,用屬性對象來做很多聰明的事情。這適用於定義的類以及動態類。我需要這一步,做一些沿着這些線路:
public static object GetDynamicObject(Dictionary<string,object> properties) {
var myObject = new object();
foreach (var property in properties) {
//This next line obviously doesn't work...
myObject.AddProperty(property.Key,property.Value);
}
return myObject;
}
public void Main() {
var properties = new Dictionary<string,object>();
properties.Add("Property1",aCustomClassInstance);
properties.Add("Property2","TestString2");
var myObject = GetDynamicObject(properties);
//Then use them like this (or rather the plug in uses them through reflection)
var customClass = myObject.Property1;
var myString = myObject.Property2;
}
圖書館正常工作與動態變量類型,具有手動分配的屬性。但是我不知道預先添加了多少或什麼屬性。
+1。備註:爲什麼不返回字典而不是動態? (至少,IDictionary)?我的意思是,返回動態是有點「誤導」,因爲你總是會返回一個字典。 – Veverke 2015-04-20 15:35:48