c# - 你能写一个可以接受任意数量参数的 c# 装饰器函数吗?

标签 c# wrapper decorator

我目前的代码非常像 python 装饰器,它接受一个函数作为参数并返回由另一个函数包装的相同函数(在本例中打开和关闭 perforce 连接)。

    public Func<TArg, TReturn> EnableP4<TReturn, TArgs>(Func<TArg, TReturn> function)
    {
        Func<TArg, TReturn> p4Wrapper = (TArg funcArg) =>
        {
            try
            {
                if (con.Status.Equals(ConnectionStatus.Disconnected)) { con.Connect(options); }
                return function(funcArg);
            }
            finally { con.Disconnect(); }
        };
        return p4Wrapper;
    }

目前这只适用于只有一个参数的函数,我想知道它是否可以变得更通用(也许有一种方法可以将数组解包到方法中?)。

(类似这样的事情?)

    public Func<TArgs, TReturn> EnableP4<TReturn, TArgs>(Func<TArgs, TReturn> function)
    {
        Func<TArgs, TReturn> p4Wrapper = (TArgs args) =>
        {
            try
            {
                if (con.Status.Equals(ConnectionStatus.Disconnected)) { con.Connect(options); }
                return function(*args);
            }
            finally { con.Disconnect(); }
        };
        return p4Wrapper;
    }

其中 TArgs 是一个 TArg[]。

最佳答案

你可以只使用 Func<T> (不是 Func<TArg,TResult> ),并允许编译器通过 lambda 表达式中的闭包为您处理多个参数。

如果您将方法更改为:

public Func<T> EnableP4<T>(Func<T> function)

你总是可以通过以下方式调用它:

var newFunc = EnableP4(() => SomeFunc(arg1, arg2, arg3));

这很好,因为它允许任意数量的参数而无需多次重载。

关于c# - 你能写一个可以接受任意数量参数的 c# 装饰器函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18363338/

相关文章:

c# - 防止 API 发生重大更改

c# - 无法加载文件或程序集 ':This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded

c# - 使用 C# .NET Core 反序列化 json

html - 如何在包装器中居中 float 左侧导航选项卡?

jquery - 使用 Jquery 在加载时显示 div

java - 如何在依赖注入(inject)框架(PicoContainer)中注册装饰对象?

Python装饰器: TypeError: function takes 1 positional argument but 2 were given

c# - 是否可以使用 C# 开发 Android 应用程序?

python - Python 的 property() 应该用作装饰器还是保存到变量中?

html - 如何为 Div 元素制作一个 Create Box-Shadow 包装器?