我正在编写一些单元测试,其中有很多形如以下的函数:
public void SomeTestHelperMethod<TKey, TValue>(TKey key, TValue value)
我正在反复调用这个函数,并使用不同的参数,就像这样。
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");
我希望能编写一个函数,它接受一个Action委托,并可以使用所有不同的参数调用委托。有没有方法可以做到这一点? 答案: 感谢MichaelCG,以下是我最终采取的措施:
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 });
}
}
我仍然对一种更普遍的方法感兴趣,但这个方法对于我的目的是有效的。