字典作为参数,其中Value-Type无关紧要

Aag*_*nor 2 c#

我有一个函数,它返回与给定值相比较的Dictionary-Keys-List的下一个更高的值.如果我们有{1,4,10,24}的键列表和给定值8,则该函数将返回10.

显然,Dictionary的Value-Part的类型对于函数,函数代码无关紧要

Dictionary<int, int> 
Run Code Online (Sandbox Code Playgroud)

Dictionary<int, myClass> 
Run Code Online (Sandbox Code Playgroud)

会是一样的.

当我想用任何字典调用函数时,方法头必须是什么样子,int是key-Type而value-Type是无关紧要的?

我试过了:

private int GetClosedKey(Dictionary<int, object> list, int theValue);
Run Code Online (Sandbox Code Playgroud)

但是当我用词典调用时,它说有非法的论点.我不想为我的函数可能被调用的每个不同的值类型复制'n'paste函数.任何想法,如何实现这一目标?

先谢谢你,弗兰克

Jon*_*eet 11

你可以把它变成通用的:

private int GetClosedKey<T>(Dictionary<int, T> list, int theValue)
Run Code Online (Sandbox Code Playgroud)

在大多数情况下,当您调用该方法时,您可以使用类型推断来避免必须为其指定类型参数T.

但是,我会考虑将其更改为:

private int GetClosedKey(ICollection<int> list, int theValue)
Run Code Online (Sandbox Code Playgroud)

然后调用它:

int value = GetClosedKey(dictionary.Keys, desiredValue);
Run Code Online (Sandbox Code Playgroud)

这使得代码更加通用 - 毕竟,没有必要将它与字典紧密结合.除了其他任何东西,这将使测试更简单.