【问题标题】:How to refactor multiple extensions with different Func parameters with same result如何使用不同的 Func 参数重构具有相同结果的多个扩展
【发布时间】:2016-11-19 12:42:45
【问题描述】:

我是 Func/Action/Predicate 的新手,我想知道重构代码的最佳方法是什么,因为我可能会有很多重复的代码。

我创建了 2 个采用 Func 参数的扩展方法(总是返回 bool):

public static void MyExtension<T>(this T obj, Func<T, bool> predicate)
    {
        do
        {
            //function code
        } while (predicate(obj));
    }
    public static void MyExtension<T1, T2>(this T1 obj, T2 OtherObject, Func<T1, T2, bool> predicate)
    {
        do
        {
            //function code
        } while (predicate(obj, OtherObject));
    }

我想要的是只对 do/while 循环进行一次编码,因为我可能有很多函数只会生成不同的 Func,但都希望运行相同的 do/while 循环。

我在想这样的事情,它接受任何 Func 参数并在每个循环上运行它。循环中的代码不关心传递给 Func 的类型。

public static void DoLoop(Func predicate)
    {
        do
        {
            //function code
        } while (predicate);
    }

但这显然行不通。有谁知道如何解决这个问题,还是我做错了什么?

最终结果是我想调用如下代码:

        var Obj = new MyObj();
        Obj.MyExtension((x) => x.Prop1.Contains("string"));

        var OtherObj = new MyObj();
        Obj.MyExtension(OtherObj, (x,y) => x.Prop1.Contains("string") && y.Prop1.Contains("other"));

谢谢。

【问题讨论】:

    标签: c# lambda func


    【解决方案1】:

    由于您的泛型方法在不同数量的泛型类型上进行了参数化,因此您需要保留所有函数签名以使调用代码能够编译。但是,您可以将实现移动到一个通用的辅助方法中以减少重复代码:

    // This is your single implementation
    private static void DoLoop(Func<bool> predicate) {
        do {
            //function code
        } while (predicate());
    }
    // These are the wrappers
    public static void MyExtension<T>(this T obj, Func<T, bool> predicate) {
         DoLoop(() => predicate(obj));
    }
    public static void MyExtension<T1, T2>(this T1 obj, T2 OtherObject, Func<T1, T2, bool> predicate) {
         DoLoop(() => predicate(obj, OtherObject));
    }
    

    包装器构造无参数谓词,并将其传递给提供实现的私有DoLoop 方法。

    【讨论】:

    • 完美!谢谢。需要稍作改动才能使其正常工作。需要更改 } while (谓词); to } while (predicate());
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-21
    相关资源
    最近更新 更多