2009-10-29 44 views
3

我正在寫一些單元測試的委託,我有很多的形式創建一個通用的功能

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 }); 
    } 
} 

我仍然有興趣在一個更常用的方法,但是這個人是我的目的功能。

+0

你的意思是讓你可以有它的對象,只是循環的清單,但實際上調用該方法的具體通用版本? – MichaelGG 2009-10-29 18:35:05

+0

就是這樣的。最後,我想比我編寫的隨機部分做出更好的測試參數,我希望能夠將它添加到此表單的所有功能中。現在我在我的單元測試中有很多重複的代碼,但是我想調用的函數(SomeTestHelperMethod)都是泛型函數。 – 2009-10-29 18:37:45

回答

6

如果我理解正確,這應該證明你正在嘗試做什麼。魔術在MakeGenericMethod中。

using System; 

class Program { 
    static void Main(string[] args) { 
     var meth = typeof(Program).GetMethod("Meth"); 
     var items = new[] { 
      new { a = (object)"hi", b = (object)1 }, 
      new { a = (object)TimeSpan.MaxValue, b = (object)DateTime.UtcNow }, 
     }; 
     foreach (var item in items) { 
      var gmeth = meth.MakeGenericMethod(item.a.GetType(), item.b.GetType()); 
      gmeth.Invoke(null, new[] { item.a, item.b }); 
     } 
    } 

    public static void Meth<A, B>(A a, B b) { 
     Console.WriteLine("<{0}, {1}>", typeof(A).Name, typeof(B).Name); 
    } 
} 

輸出:

<String, Int32> 
<TimeSpan, DateTime> 
+0

有趣的,我會試試看。 – 2009-10-29 19:01:08

+0

請注意,如果您將「SomeTestHelperMethod」重載或使其非公開。 – Tinister 2009-10-29 19:32:11

+0

這是單元測試,所以我不認爲我會永遠關心,但這是很好的知道。 – 2009-10-29 19:50:23