开发者

Dictionary as parameter, where the Value-Type is irrelevant

开发者 https://www.devze.com 2022-12-22 21:27 出处:网络
I have a function, that returns the next higher value of a Dictionary-Keys-List compared to a given value. If we have a Key-List of {1, 4, 10, 24} and a given value of 8, the function would return 10.

I have a function, that returns the next higher value of a Dictionary-Keys-List compared to a given value. If we have a Key-List of {1, 4, 10, 24} and a given value of 8, the function would return 10.

Obviously the type of the Value-Part of the Dictionary doesn't matter for the function, the function-code for a

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 f开发者_开发问答unction with any Dictionary, that has int as key-Type and the value-Type is irrelevant?

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. 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.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号