我正在写一些单元测试的委托,我有很多的形式创建一个通用的功能
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 });
}
}
我仍然有兴趣在一个更常用的方法,但是这个人是我的目的功能。
你的意思是让你可以有它的对象,只是循环的清单,但实际上调用该方法的具体通用版本? – MichaelGG 2009-10-29 18:35:05
就是这样的。最后,我想比我编写的随机部分做出更好的测试参数,我希望能够将它添加到此表单的所有功能中。现在我在我的单元测试中有很多重复的代码,但是我想调用的函数(SomeTestHelperMethod)都是泛型函数。 – 2009-10-29 18:37:45