2009-10-29 81 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