在C#java.lang.Number中的等效

问题描述 投票:2回答:1

我要让字典之间的算术运算与数字的值。这是我的代码:

public class DictionaryOperation {

    public static Dictionary<TKey, double> Add<TKey>(Dictionary<TKey, double> d1, Dictionary<TKey, double> d2) {
        Dictionary<TKey, double> result = new Dictionary<TKey, double>();
        foreach (TKey key in d1.Keys) {
            if (d2.ContainsKey(key))
                result[key] = d1[key] + d2[key];
            else
                result[key] = d1[key];
        }
        foreach (TKey key in d2.Keys) {
            if (!result.ContainsKey(key))
                result[key] = d2[key];
        }
        return result;
    }
}

我想知道如果我可以为任何数值类型只能创建一个方法(INT浮动,小数,...)或者我必须创建每个数值类型的一种方法,这意味着将在每个方法相同的代码。

我希望能够做到这一点:

Dictionary<string, int> ints = DictionaryOperation.Add(new Dictionary<string, int>(), new Dictionary<string, int>());
Dictionary<string, float> floats = DictionaryOperation.Add(new Dictionary<string, float>(), new Dictionary<string, float>());
c#
1个回答
2
投票

您可避免使用泛型写每一个数字类型的方法相同。你已经在你的字典中的通用密钥。唯一缺少的是通用的价值。改变你的方法用一个通用的字典值:

public static Dictionary<TKey, TValue> Add<TKey, TValue>(Dictionary<TKey, TValue> d1, Dictionary<TKey, TValue> d2) 
    where TValue : IComparable

问题是,不存在类型约束,只允许数字(或可与+运算被添加的对象)。我用IComparable的线之上,因为所有的数字类型是可比的。

接下来的问题是,在IComparable不尝试使用+操作时有所帮助。为此,您可以使用动态像这样:

dynamic a = d1[key];
dynamic b = d2[key];
result[key] = a + b;

现在你可以使用为实现IComparable所有类型的方法。但你有没有编译时的安全性。这意味着你将得到运行时错误对于不执行+运营商的所有类型。

这个问题已经在这里描述:C# Adding two Generic Values

在这里,完整的方法:

public static Dictionary<TKey, TValue> Add<TKey, TValue>(Dictionary<TKey, TValue> d1, Dictionary<TKey, TValue> d2) 
        where TValue : IComparable
    {
        Dictionary<TKey, TValue> result = new Dictionary<TKey, TValue>();
    foreach (TKey key in d1.Keys) {
        if (d2.ContainsKey(key))
        {
            dynamic a = d1[key];
            dynamic b = d2[key];
            result[key] = a + b;
        }
        else
            result[key] = d1[key];
    }
    foreach (TKey key in d2.Keys) {
        if (!result.ContainsKey(key))
            result[key] = d2[key];
    }
    return result;
}
© www.soinside.com 2019 - 2024. All rights reserved.