代码之家  ›  专栏  ›  技术社区  ›  fhcimolin Sofox

如何在C反射中添加到列表中?[复制品]

  •  -1
  • fhcimolin Sofox  · 技术社区  · 7 年前

    这个问题已经有了答案:

    当我迭代一个通用对象的属性时,我可能会发现 List<T> .

    到目前为止,我已经能够初始化列表,但我似乎无法 如何获取列表类型,初始化对象,将数据放入其中,最后添加到列表中?

    这是代码,我被卡住的地方:

    private static void FillMePlease<T>(T genericThingy)
    {
        foreach (PropertyInfo propertyInfo in genericThingy.GetType().GetProperties())
        {
            if (propertyInfo.PropertyType == typeof(string))
            {
                propertyInfo.SetValue(genericThingy, "Test", null);
            }
            else
            {
                //var list = Activator.CreateInstance(propertyInfo.PropertyType);
                //Now I'm stumped.
            }
        }
    }
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   canton7    7 年前

    List<T>

    type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>)
    

    T

    elementType = type.GetGenericArguments()[0]
    

    typeof(List<>).MakeGenericType(elementType)
    

    var methodInfo = type.GetMethod("Add");
    methodInfo.Invoke(list, new object[] { itemToAdd });