繁体   English   中英

什么是 C# 相当于 Python 的 functools.partial?

[英]What is C# equivalent of Python's functools.partial?

在 python 中我们有一个functools.partial机制。 什么是有效的 C# 等价物?

对于那些不熟悉这个概念的人,我正在寻找一般情况,但它可以是任何东西,甚至:

def add(a: int, b: int):
    return a + b

add_to_one = partial(add, 1)
add_to_one(2)  # This will return 3

根据您的示例,我能想到的最好的是Func delegate

这提供了一种基于几乎任何东西定义本地 function 的方法。 在本例中,它在本地Main scope 中定义。

用法:

using System;
                    
public class Program
{
    public static void Main()
    {
       // Func<,> type: input is 'int', output will be 'int'
       // 'c' = input argument.
       // '=>' indicates what will be done with it.  
       Func<int,int> add_to_one = (c) => Add(c,1);

       //call 'add_to_one' as a normal method.
       int result = add_to_one(2);
       
       Console.WriteLine(result);
    }
    
    //example method
    public static int Add(int a, int b)
    {
        return a + b;
    }
}

Output:

3

至于一般情况:

返回一个新的部分 object,当调用它时,其行为类似于使用位置 arguments args 和关键字 arguments 关键字调用的 func。 如果向调用提供了更多 arguments,它们将附加到 args。

这部分被覆盖。 您将拥有一个行为类似于方法/函数的可调用变量。

至于这个:

如果提供了附加关键字 arguments,它们将扩展和覆盖关键字。

有可能,该结构可扩展到更多输入变量,例如:

// 3 inputs
// output is string
Func<int,string,double,string> foo = (i,s,d) => $"int: {i}, string: {s}, double {d}";

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM