【问题标题】:Base Type to add two objects?添加两个对象的基本类型?
【发布时间】:2015-08-04 21:52:15
【问题描述】:

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

// 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 类型定义了一个对象是 summable

【问题讨论】:

  • private void MergeStats&lt;T&gt;(T src, T target) where T : ISummable { }?
  • struct 会得到你intfloat(和朋友),但它显然是一个不精确的约束。
  • 您可以使用dynamic 执行此操作,但这也会添加strings 和任何其他具有+ 运算符的类型。您需要缩小可以添加的类型。还是您真的想要所有可以添加的类型?

标签: c#


【解决方案1】:

不,.NET 框架中没有描述可求和或由可求和属性组成的对象的基本类型。类型约束可能有助于确保传递给方法的srctarget 是相同的类型,以便您的属性比较循环能够正常工作。这只是一个void MergeStats&lt;T&gt;(T src, T target),其中 T 将在方法主体中未使用。

【讨论】:

    【解决方案2】:

    类似:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-17
      • 1970-01-01
      • 2020-02-24
      • 2020-05-19
      相关资源
      最近更新 更多