【发布时间】:2022-10-18 22:57:29
【问题描述】:
是否可以在 C# 中将方法组作为参数传递?
我正在使用很多模拟。我有以下内容:
public static List<IInvocation> InvocationsWithName<T>(
this Mock<T> mock, string methodName)
where T: class
{
var invocations = mock.Invocations.Where(i => i.Method.Name == methodName).ToList();
return invocations;
}
我这样使用它:
var invocations = myInterface.InvocationsWithName(nameof(MyInterface.MyMethod));
有用。但我更喜欢这样使用它:
var invocations = myInterface.InvocationsWithName(MyInterface.MyMethod);
为此,我需要以接受 MyInterface.MyMethod 作为参数的方式定义我的 InvocationsWithName 扩展方法。但我不知道是否/如何做到这一点。
在实践中,MyMethod 可能是单个方法,也可能是具有多个成员的方法组。理想情况下,该解决方案在这两种情况下都适用。
【问题讨论】:
-
只需使用
Func<T>而不是 methodName
标签: c# moq method-group