I'm writing some unit tests and I have a lot of functions of the form
public void SomeTestHelperMethod<TKey, TValue>(TKey key, TValue value)
which I'm calling repeatedly with various arguments like this
SomeTestHelperMethod<int, int>(0, 1);
SomeTestHelperMethod<int, object>(1, new Nullable<double>(16.5));
SomeTestHelperMethod<int, string>(2, "The quick brown fox jumped over the lazy dog.");
SomeTestHelperMethod<object, int>(new NullReferenceException(), 15);
SomeTestHelperMethod<object, object>(StringComparison.Ordinal, new Version());
SomeTestHelperMethod<object, string>((ushort)3, string.Empty);
SomeTestHelperMethod<string, int>(string.Empty, 195);
SomeTestHelperMethod<string, object>("A string", this);
SomeTestHelperMethod<string, string>("Another string", "Another string");
What I'd like to do is write a function that takes an Action delegate and can Invoke the delegate with all of the different arguments. Is there any way to do it?
Answer:
Thanks to MichaelCG here's what I ended up doing:
private void CallWithKeyAndValue(string methodName)
{
MethodInfo method = typeof(ObservableDictionaryTest).GetMethod(methodName);
foreach (KeyValuePair<object, object> kvp in ourKeyValueSet)
{
MethodInfo genericMethod = method.MakeGenericMethod(kvp.Key.GetType(), kvp.Value.GetType());
genericMethod.Invoke(this, new[] { kvp.Key, kvp.Value });
}
}
I'd still be interested in a more general method but this one is functional for my purposes.
If I understand you correctly, this should demonstrate what you are trying to do. The magic is in MakeGenericMethod.
Outputs: