簡體   English   中英

c#遞歸反射和通用列表設置默認屬性

[英]c# Recursive Reflection & Generic Lists setting default properties

我試圖使用反射來實現以下目的:

我需要一個方法,我傳入一個對象,這個方法將遞歸實例化具有子對象的對象,並使用默認值設置屬性。 我需要實例化整個對象,根據需要進行多個級別。

此方法需要能夠處理具有多個屬性的對象,這些屬性將是其他對象的通用列表。

這是我的示例代碼(當我得到一個包含List<AnotherSetObjects>的對象時,我得到一個參數計數不匹配異常:

private void SetPropertyValues(object obj)
{
    PropertyInfo[] properties = obj.GetType().GetProperties();

    foreach (PropertyInfo property in properties)
    {
        if (property.PropertyType.IsClass && property.PropertyType != typeof(string) && property.PropertyType.FullName.Contains("BusinessObjects"))
        {
            Type propType = property.PropertyType;

            var subObject = Activator.CreateInstance(propType);
            SetPropertyValues(subObject);
            property.SetValue(obj, subObject, null);
        }
        else if (property.PropertyType == typeof(string))
        {
            property.SetValue(obj, property.Name, null);
        }
        else if (property.PropertyType == typeof(DateTime))
        {
            property.SetValue(obj, DateTime.Today, null);
        }
        else if (property.PropertyType == typeof(int))
        {
            property.SetValue(obj, 0, null);
        }
        else if (property.PropertyType == typeof(decimal))
        {
            property.SetValue(obj, 0, null);
        }
    }
}

謝謝

您可以通過檢查property.PropertyType.IsGeneric來篩選出來,這對於通用容器是真的。 如果需要,還要檢查property.PropertyType.IsArray

此外,您可能還想避免使用非通用容器。 在這種情況下,測試對象是否是這種容器的接口類型。 例如 - IList

bool isList(object data)
{
    System.Collections.IList list = data as System.Collections.IList;
    return list != null;
}

...
if (isList(obj)) {
    //do stuff that take special care of object which is a List
    //It will be true for generic type lists too!
}

這是一個棘手的:)

當您將包含某些“BusinessObjects”類型的通用列表的對象作為屬性傳遞給初始化程序時,此屬性將通過您的屬性

if (property.PropertyType.IsClass && property.PropertyType != typeof(string) && property.PropertyType.FullName.Contains("BusinessObjects"))

表達式,因為實例化的泛型類型將具有如下名稱:

System.Collections.Generic.List`1[[ConsoleApplication92.XXXBusinessObjects, ConsoleApplication92, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]

這導致使用List本身作為參數調用初始化方法。 該列表將有一個名為Item的SomeBusinessObjects類型的索引器。 這也將通過上述條件,因此您也會嘗試初始化它。 它的結果是這樣的:

obj.ListProperty.Item = new SomeBusinessObject();

而索引器只能在這樣的初始化中使用

obj.ListProperty[0] = new SomeBusinessObject();

這表明,確實,你缺少一個參數。

你要做的就是取決於你:)

暫無
暫無

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

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