我正在寫一些單元測試的委託,我有很多的形式創建一個通用的功能
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