简体   繁体   English

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

[英]Dictionary as parameter, where the Value-Type is irrelevant

I have a function, that returns the next higher value of a Dictionary-Keys-List compared to a given value. 我有一个函数,它返回与给定值相比较的Dictionary-Keys-List的下一个更高的值。 If we have a Key-List of {1, 4, 10, 24} and a given value of 8, the function would return 10. 如果我们有{1,4,10,24}的键列表和给定值8,则该函数将返回10。

Obviously the type of the Value-Part of the Dictionary doesn't matter for the function, the function-code for a 显然,Dictionary的Value-Part的类型对于函数,函数代码无关紧要

Dictionary<int, int> 

and

Dictionary<int, myClass> 

would be the same. 会是一样的。

How has the method-head have to look like, when I want to call the function with any Dictionary, that has int as key-Type and the value-Type is irrelevant? 当我想用任何一个字典调用函数时,方法头必须是什么样子,int是key-Type而value-Type是无关紧要的?

I tried: 我试过了:

private int GetClosedKey(Dictionary<int, object> list, int theValue);

but it says that there are illegal arguments, when I call it with a Dictionary. 但是当我用词典调用时,它说有非法的论点。 I don't want to copy'n'paste the function for each different value-type that my function may be called. 我不想为我的函数可能被调用的每个不同的值类型复制'n'paste函数。 Any idea, how to accomplish that? 任何想法,如何实现这一目标?

Thanks in advance, Frank 先谢谢你,弗兰克

You can make it generic: 你可以把它变成通用的:

private int GetClosedKey<T>(Dictionary<int, T> list, int theValue)

In most cases, when you call the method you can use type inference to avoid having to specify the type argument for T . 在大多数情况下,当您调用方法时,您可以使用类型推断来避免必须为T指定类型参数。

However, I would consider changing it to: 但是,我会考虑将其更改为:

private int GetClosedKey(ICollection<int> list, int theValue)

And then calling it with: 然后调用它:

int value = GetClosedKey(dictionary.Keys, desiredValue);

That makes the code more general - there's no need to couple it tightly with a dictionary, after all. 这使代码更加通用 - 毕竟,没有必要将它与字典紧密结合。 Aside from anything else, that's going to make it simpler to test. 除了其他任何东西,这将使测试更简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM