一千萬個為什麽

搜索

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

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

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

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

Here is my sample code (I am getting a parameter count mismatch exception when i get an object containing a List:

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);
        }
    }
}

謝謝

最佳答案

You can filter out by checking for property.PropertyType.IsGeneric which is true for generic containers. If you need, also check for property.PropertyType.IsArray.

Moreover, you may also want to avoid non-generic containers. In that case, test for object to be of interface types of such containers. Eg - 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!
}

轉載註明原文: c#遞歸反射和通用列表設置默認屬性