C#将未知类型的项添加到从对象类型推断的类型的数组/列表/ etc中

时间:2015-10-21 14:00:18

标签: c# arrays collections types

我很难找到一种方法将对象添加到数组中而不知道任何一个对象的类型...所以基本上,我们使用从文本文件导入的数据来填充对象。我们填充的对象会有所不同,我们使用反射来识别对象,以找到与txt文件中提供的字符串具有相同类类型的对象。该类的字符串表示形式是我们在整个过程中所拥有的类的唯一知识。当我们有需要创建的对象然后放入数组时会出现问题。我能够识别它所属的数组,但是将该对象存储在集合中是另一回事。

就我而言:

更新:

public bool Populate(Dictionary<string, string> nameValuePairs, object obj) 
            {
                return obj.GetType() == typeof (Array) ? PopulateList(nameValuePairs, obj)  : PopulateObject(nameValuePairs, obj);
            }

private bool PopulateObject<T>(Dictionary<string, string> nameValuePairs, T obj) where T : new()
    {
        foreach (var kvp in nameValuePairs)
        {
            var itemName = kvp.Key;
            var value = kvp.Key;

            try
            {
                var property = obj.GetType().GetProperty(itemName, BindingFlags.Public | BindingFlags.Instance);
                property?.SetValue(obj, value);

            }
            catch (Exception e)
            {
                try
                {
                    var field = obj.GetType().GetField(itemName, BindingFlags.Public | BindingFlags.Instance);
                    field?.SetValue(obj, value);
                }
                catch (Exception e1)
                {

                    return false;
                }
            }
        }

        return true;
    }

    private bool PopulateList<T>(Dictionary<string, string> itemProperties, List<T> list)
             where T : new()
    {
        var baseObj = new T();
        var lookup = new NameLookupHandler();

        Populate(itemProperties, baseObj);
        list.Add(baseObj);
        return true;
    }

private bool PopulateList(Dictionary<string, string> itemProperties, ref object list)
{
        Type baseType = list.GetType().GetElementType();
        var baseObj = Activator.CreateInstance(baseType);
        //Code here populates the object that will be added to the collection.


        return true;
}

更新方法:

private bool PopulateList<T>(Dictionary<string, string> itemProperties, List<T> list)
                 where T : new()
        {
            var baseObj = new T();
            var lookup = new NameLookupHandler();

            Populate(itemProperties, baseObj);
            list.Add(baseObj);
            return true;
        }

1 个答案:

答案 0 :(得分:3)

为什么不把它变成通用的?

private bool PopulateList<T>(Dictionary<string, string> itemProperties, List<T> list)
                 where T : new();
{

        var baseObj = new T();
        //Code here populates the object that will be added to the collection.

        list.Add(baseObj); <--- This obviously doesn't work.
        return true;
}

请注意list参数必须为ref,除非您更改了list个引用。它不需要ref即可将项目添加到列表中。