添加两个对象的基本类型

本文关键字:类型 对象 两个 添加 | 更新日期: 2023-09-27 18:06:18

我想通过两个对象中的每个属性合并两个对象,如:

// 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 : ??? { }

所以我的问题是:是否存在定义一个对象是可求和的的基础类型?

添加两个对象的基本类型

不,在。net框架中没有描述可求和的对象或由可求和属性组成的对象的基类型。类型约束可能有助于确保传递给方法的srctarget具有相同的类型,以便您的属性比较循环能够工作。这将是一个简单的void MergeStats<T>(T src, T target),其中T将在方法体中不被使用。

类似于

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*/
}