public class MyClass
{
public MyClass()
{
myDictionary = new Dictionary<string, string>();
myArray = new List<int>();
}
private Dictionary<string, string> myDictionary;
public Dictionary<string, string> MyDictionary
{
get { return myDictionary; }
}
private List<int> myArray;
public List<int> MyArray
{
get { return myArray; }
}
}
static void Main(string[] args)
{
var model = new MyClass();
Type t = model.GetType();
System.Reflection.PropertyInfo[] properties = t.GetProperties();
//Add items to MyArray and MyDictionary in this model According to the properties using reflection
}
我想在此模型中向Array和Dictionary添加项目根据使用反射的属性。 谢谢您的帮助 !
答案 0 :(得分:0)
要将项目添加到Generic.List<T>
,请使用Add
方法
示例:
MyArray.Add(1);
对于Generic.Dictonary<T>
,您还使用Add
方法,但提供2个值,键和值
MyDictionary.Add("MyKey", "MyValue");
因此,您可以循环使用PropertyInfo[]
,并将所需内容添加到List<T>
或Dictionary<T>
foreach(var prop in properties )
{
MyArray.Add(a number from somewhere);
MyDictionary("some key", "some value");
}
答案 1 :(得分:0)
var dictProp = properties.Single(t => t.Name = "MyDictionary");
var myDict = (Dictionary<string,string>)dictProp.GetValue(model, null);
myDict.Add("MyKey", "MyValue");