2017-03-16 32 views
0

我试图做一个泛型类,它能够更新对象的任何属性。通用对象更新器 - 将数组转换为列表

我使它适用于多种情况,例如,单值属性(int,string,bool等)。如果属性为IEnumerable<T>,那么它也可以很好地工作,在这种情况下,列表或数组可以正常工作。

但是如果属性为List<T>,那么我会碰壁,但要分配的值是Array(或其他方式)。在“标准”情况下,我可以简单地使用ToList()ToArray,但在一般情况下,我很困惑如何。

下面的代码

public static class ObjectUpdater 
{ 
    public static T Patch<T>(T obj, IEnumerable<KeyValuePair<string, object>> delta) 
    { 
     if (obj == null || delta == null) 
     { 
      return obj; 
     } 
     foreach (var deltaItem in delta) 
     { 
      Patch(obj, deltaItem.Key, deltaItem.Value); 
     } 
     return obj; 
    } 

    private static void Patch<T>(T obj, string propertyName, object value) 
    { 
     var propertyInfo = obj.GetType().GetProperty(propertyName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance); 
     if (propertyInfo == null || !propertyInfo.CanRead || !propertyInfo.CanWrite) 
     { 
      throw new ArgumentException($"Property '{propertyName}' doesn't exist or cannot be updated"); 
     } 
     SetPropertyValue(obj, value, propertyInfo); 
    } 

    private static void SetPropertyValue(object obj, object value, PropertyInfo propertyInfo) 
    { 
     if (propertyInfo.PropertyType.IsEnum) 
     { 
      propertyInfo.SetValue(obj, Convert.ToInt32(value)); 
      return; 
     } 

     // property parsing is based on the target property's TryParse() method 
     // big/small enough float/DateTime values had issues, as the ToString() might lose precision >> they're handled separately 
     if (value is float) 
     { 
      SetPropertyValueAsFloat(obj, (float)value, propertyInfo); 
      return; 
     } 

     if (value is DateTime) 
     { 
      SetPropertyValueAsDateTime(obj, (DateTime)value, propertyInfo); 
      return; 
     } 

     var systemType = propertyInfo.PropertyType.UnderlyingSystemType; 
     var tryParse = systemType.GetMethod("TryParse", new[] {typeof(string), systemType.MakeByRefType()}); 
     if (tryParse == null) 
     { 
      propertyInfo.SetValue(obj, value); 
      return; 
     } 
     var parameters = new object[] 
         { 
          value.ToString(), 
          null 
         }; 
     var canParse = (bool) tryParse.Invoke(null, parameters); 
     propertyInfo.SetValue(obj, canParse ? parameters[1] : value); 
    } 

    private static void SetPropertyValueAsDateTime(object obj, DateTime value, PropertyInfo propertyInfo) 
    { 
     // code to handle DateTime value 
    } 
} 

// and two test methods 
[Fact] 
private void Patch_StringListPropertyFromArrayValue() 
{ 
    var sourceObject = new TestClassWithCollectionProperties 
         { 
          StringListProperty = null 
         }; 
    var expectedResult = new TestClassWithCollectionProperties 
         { 
          StringListProperty = new List<string> 
                { 
                 "abc", 
                 "def" 
                } 
         }; 
    var delta = new List<KeyValuePair<string, object>> 
       { 
        new KeyValuePair<string, object>("StringListProperty", 
         new [] 
         { 
          "abc", 
          "def" 
         }) 
       }; 

    var result = ObjectUpdater.Patch(sourceObject, delta); 

    result.ShouldBeEquivalentTo(expectedResult); 
} 

[Fact] 
private void Patch_StringArrayPropertyFromListValue() 
{ 
    var sourceObject = new TestClassWithCollectionProperties 
         { 
          StringArrayProperty = null 
         }; 
    var expectedResult = new TestClassWithCollectionProperties 
         { 
          StringArrayProperty = new[] 
                { 
                 "abc", 
                 "def" 
                } 
         }; 
    var delta = new List<KeyValuePair<string, object>> 
       { 
        new KeyValuePair<string, object>("StringArrayProperty", 
         new List<string> 
         { 
          "abc", 
          "def" 
         }) 
       }; 

    var result = ObjectUpdater.Patch(sourceObject, delta); 

    result.ShouldBeEquivalentTo(expectedResult); 
} 

但该试验作为ObjectUpdater.Patch抛出一个System.ArgumentException以下消息类型的

对象“System.String []”不能被转换为类型失败“系统.Collections.Generic.List`1 [System.String]”。

有什么建议吗?

+0

嗯..你可以试试你的清单,'.ToArray转换成数组()'做你的东西,并将其转换回循环内的'List'也许? – uTeisT

回答

1

那么,你可以前tryParse尝试像这样的东西在某处的代码处理的具体情况:上述

if (value != null && value.GetType() != propertyInfo.PropertyType 
    // from T[] 
    && value.GetType().IsArray && value.GetType().GetArrayRank() == 1 
    // to List<T> 
    && propertyInfo.PropertyType.IsGenericType 
    && propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(List<>) 
    && propertyInfo.PropertyType.GetGenericArguments()[0] == value.GetType().GetElementType()) 
{ 
    var T = value.GetType().GetElementType(); 
    var listT = typeof(List<>).MakeGenericType(T); 
    // new List<T>(IEnumerable<T> items) 
    var enumerableT = typeof(IEnumerable<>).MakeGenericType(T); 
    var newListT = listT.GetConstructor(new Type [] { enumerableT }); 
    var list = newListT.Invoke(new[] { value }); 
    propertyInfo.SetValue(obj, list); 
    return; 
} 

处理分配形式T[]List<T>。为了处理相反的分配,通过反射增加一个类似if条件与类型互换,简单地调用List<T>.ToArray)方法:

if (value != null && value.GetType() != propertyInfo.PropertyType 
    // to T[] 
    && propertyInfo.PropertyType.IsArray && propertyInfo.PropertyType.GetArrayRank() == 1 
    // from List<T> 
    && value.GetType().IsGenericType 
    && value.GetType().GetGenericTypeDefinition() == typeof(List<>) 
    && value.GetType().GetGenericArguments()[0] == propertyInfo.PropertyType.GetElementType()) 
{ 
    // List<T>.ToArray() 
    var toArray = value.GetType().GetMethod("ToArray", Type.EmptyTypes); 
    var array = toArray.Invoke(value, null); 
    propertyInfo.SetValue(obj, array); 
    return; 
} 
+0

是的,它确实处理阵列>>列表案例。你是否也可以提供List >> Array方案的版本? – Szeki

+0

当然。您只需要检测该案例并通过反射调用'List .ToArray'方法。但请注意,你正在进入无限循环:) –

+0

无论如何,你走了。 –