C# - 代码有什么问题(泛型,静态方法等)

Gre*_*reg 1 .net c# generics

我在下面的代码中得到了"无法从'int'转换为'TValue'".我怎样才能解决这个问题?我理解为什么会出现问题,但我想知道最好的方法.我是否需要决定特定类型的ReturnValuesDict,而不是让它通用?

public class ReturnValuesDict<TKey, TValue> : CloneableDictionary<TKey, TValue>
{

    public static ReturnValuesDict<TKey, TValue> CreateEmptyClone(ReturnValuesDict<TKey, TValue> current) 
    {
        var newItem = new ReturnValuesDict<TKey, TValue>();
        foreach (var curr in current)
        {
            newItem.Add(curr.Key, 0);  // ERROR on the 2nd parameter here
        }
        return newItem;
    }

}
Run Code Online (Sandbox Code Playgroud)

Ani*_*Ani 12

这不编译的原因是0(an int)通常不能转换为字典值'type(TValue),就编译器而言,它是某种任意类型.(where TValue : int不行,但这是另一回事)

我假设您正在尝试使用与原始键相同的键来构造字典,但使用"空"值?

如果您认为.NET认为是类型的"默认"值,您可以尝试将该行更改为:

newItem.Add(curr.Key, default(TValue));  
Run Code Online (Sandbox Code Playgroud)

这将使用字典值的类型的默认值.例如:null对于引用类型,对于数值类型为零.

另一方面,如果想要编写一个仅适用于具有int值的字典的方法,则可以使其更具限制性(将其置于另一个类中):

public static ReturnValuesDict<TKey, int> CreateEmptyClone<TKey>(ReturnValuesDict<TKey, int> current) 
{
    var newItem = new ReturnValuesDict<TKey, int>();
    foreach (var curr in current)
    {
        newItem.Add(curr.Key, 0);  
    }
    return newItem;
}
Run Code Online (Sandbox Code Playgroud)

请注意,该方法现在是采用无约束通用TKey参数的通用方法.