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.
精彩评论