0
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
}

我想根据使用反射的属性将项目添加到此模型中的 MyArray 和 MyDictionary 中。谢谢您的帮助 !

4

2 回答 2

0

要将项目添加到Generic.List<T>您使用的Add方法

例子:

MyArray.Add(1);

因为Generic.Dictonary<T>您也使用该Add方法,但提供 2 个值,Key 和 Value

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");
}
于 2013-08-15T02:55:01.843 回答
0
var dictProp = properties.Single(t => t.Name = "MyDictionary");
var myDict = (Dictionary<string,string>)dictProp.GetValue(model, null);
myDict.Add("MyKey", "MyValue");
于 2013-08-15T02:58:31.120 回答