如何为类中的每个属性创建单独的列表

时间:2014-04-24 03:06:48

标签: c#

我在课堂下面,

public class class1
{
  public int prop1 {get; set;}
  public string prop2 {get; set;}
  public bool prop3 {get; set;}
}

public class class2
{
   public int prop1 {get; set;}
   public List<string> prop2 {get; set;}
}

Now, for each property in class1 i need to build List<class2>.

请告诉我,如何在c#4.0中完成此操作?

提前致谢!!

1 个答案:

答案 0 :(得分:0)

您可以执行此C#newish“dynamic”关键字和ExpandoObject,但动态创建动态类型的通用列表非常棘手。

我认为这应该适用:

        dynamic myDynamicClass = new ExpandoObject();

        foreach (var prop in typeof (Foo).GetProperties()) {
            Type[] typeArgs = {prop.GetType()};
            var listImplementationType = typeof (List<>).MakeGenericType(typeArgs);
            var myList = Activator.CreateInstance(listImplementationType);
            myDynamicClass[prop.Name] = myList;    
        }