我想通过两个对象中的每个属性合并两个对象,如:
// simplified pseudo code
foreach property which is in both objects (compared by name) do
target.Property += src.Property;
我目前的方法如下:
private void MergeStats(Object src, Object target)
{
if (src == null || target == null) return;
foreach (var srcProperty in src.GetType().GetProperties())
{
var targetProperty = target.GetType().GetProperty(srcProperty.Name);
if (targetProperty == null) { continue; }
if (targetProperty.GetValue(target).GetType() != typeof(UInt32)) { continue; }
if (srcProperty.GetValue(src).GetType() != typeof(UInt32)) { continue; }
var currentValue = (UInt32)(targetProperty.GetValue(target));
var itemValue = (UInt32)(srcProperty.GetValue(src));
var newValue = currentValue + itemValue;
target.GetType().GetProperty(srcProperty.Name).SetValue(target, newValue);
}
}
但是我想这样做更通用:
private void MergeStats<T>(Object src, Object target) where T : ??? { }
所以我的问题是:是否有任何Baste Type定义一个对象是 summable ?
答案 0 :(得分:1)
不,.NET框架中没有基类型描述可求和的对象,或者由可求属性组成。类型约束可能有助于确保传递给方法的src
和target
具有相同的类型,以便您的属性比较循环起作用。这只是void MergeStats<T>(T src, T target)
,其中T将在方法体中未使用。
答案 1 :(得分:0)
类似的东西:
private void T MergeStats<T, TSource, TTarget>(TSource source, TTarget target) where T : new()
{
/* Use reflection to get a dictionary from T where the key is the property name and the value the type. Now you can do the same for your source and target, lastly looping the dictionary from T and checking if key exists in either source or target dictionary, add property value to T*/
}