我知道存在一些解决此问题的问题,但答案通常沿着推荐字典或参数集合的路线行事,这在我的情况下不起作用。在运行时动态添加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