【问题标题】:Pass a C# method group?传递一个 C# 方法组?
【发布时间】: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&lt;T&gt; 而不是 methodName

标签: c# moq method-group


【解决方案1】:

您的描述有点模糊,但它尖叫着表达:

static List<IInvocation> InvocationsWithName<TInvocations, TClass, TMethod>(
    this TInvocations mock, TClass @class, Expression<Func<TClass, TMethod>> selector)
    where TInvocations : class, IInvocationsContainer
    where TClass : class
{
    var invocations = mock.Invocations
        .Where(i => i.MethodName == ((MemberExpression)selector.Body).Member.Name).ToList();
    return invocations;
}

public static void Main()
{
    // called like this
    var invocations = InvocationsWithName(new InvocationsContainer(), new C(), c => c.F);
}

其中C 是包含要获取其名称的函数的类:

class C
{
    public int F { get; set; }
}

【讨论】:

    猜你喜欢
    • 2016-12-21
    • 2010-10-23
    • 2017-11-15
    • 1970-01-01
    • 1970-01-01
    • 2011-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多