簡體   English   中英

C#將未知類型的項添加到從對象類型推斷的類型的數組/列表/ etc中

[英]C# Adding items of unknown types to an array/list/etc of a type inferred from an object type

我很難找到一種方法將對象添加到數組中而不知道任何一個對象的類型...所以基本上,我們使用從文本文件導入的數據來填充對象。 我們填充的對象會有所不同,我們使用反射來識別對象,以找到與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;
        }

為什么不把它變成通用的?

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將項添加到列表中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM