创建通用函数的委托
我正在编写一些单元测试,并且我有很多形式的函数
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 });
}
}
我仍然对一种更通用的方法感兴趣,但这个方法对于我的目的来说是有用的。
I'm writing some unit tests and I have a lot of functions of the form
public void SomeTestHelperMethod<TKey, TValue>(TKey key, TValue value)
which I'm calling repeatedly with various arguments like this
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");
What I'd like to do is write a function that takes an Action delegate and can Invoke the delegate with all of the different arguments. Is there any way to do it?
Answer:
Thanks to MichaelCG here's what I ended up doing:
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 });
}
}
I'd still be interested in a more general method but this one is functional for my purposes.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果我理解正确的话,这应该表明你正在尝试做什么。神奇之处在于 MakeGenericMethod。
输出:
If I understand you correctly, this should demonstrate what you are trying to do. The magic is in MakeGenericMethod.
Outputs: