Bry*_*son 3 .net lambda delegates generic-function
我正在写一些单元测试,我有很多表单的功能
public void SomeTestHelperMethod<TKey, TValue>(TKey key, TValue value)
Run Code Online (Sandbox Code Playgroud)
我正在反复调用这样的各种论点
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");
Run Code Online (Sandbox Code Playgroud)
我想做的是编写一个带有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 });
}
}
Run Code Online (Sandbox Code Playgroud)
我仍然对更通用的方法感兴趣,但这个方法对我的目的是有用的.
如果我理解正确,这应该证明你要做的事情.魔术在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);
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
<String, Int32>
<TimeSpan, DateTime>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
363 次 |
| 最近记录: |