我试图做一个泛型类,它能够更新对象的任何属性。通用对象更新器 - 将数组转换为列表
我使它适用于多种情况,例如,单值属性(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]”。
有什么建议吗?
嗯..你可以试试你的清单,'.ToArray转换成数组()'做你的东西,并将其转换回循环内的'List'也许? – uTeisT