我知道有一些问题针对这个进行了讨论,但答案通常是推荐使用字典或参数集合,并且在我的情况下不起作用。
我正在使用一个库,通过反射来处理具有属性的对象。这适用于已定义的类,以及动态类。我需要更进一步,做出以下操作:
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;
}
这个库可以与动态变量类型一起正常工作,并且可以手动分配属性。但是,我不知道预先会添加多少或者哪些属性。
Dictionary<string, object>
类型。 - Stefan Golubović