如何像python那样返回c函数?

2024-10-02 00:27:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试做一些在python中可以做到的事情:

class Spam():
    def print_four_numbers(a, b, c, d):
        print a, b, c, d

class Beacon():
    def bar(SpamInstance):
        return SpamInstance.print_four_numbers

B, S = Beacon(), Spam()

这里的关键是上面的代码允许我这样做:

>>>B.bar(S)(1, 2, 3, 4)
1 2 3 4

如何使用C#执行类似的操作?如果它改变了什么,我需要“print\u four\u numbers”方法重载3-4次。我读过关于代表和事件的文章,但是他们在这里工作吗(以及如何工作)?你知道吗

我也知道,这可以通过简单地将所有这些参数传递给bar()并将它们“传递”给另一个函数来解决,但是我不喜欢有很多参数的方法。你知道吗

谢谢!你知道吗


Tags: 方法代码returndefbar代表spam事情
1条回答
网友
1楼 · 发布于 2024-10-02 00:27:29
class Spam
{
    public void PrintFourNumbers(int a, int b, int c, int d)
    {
        Console.WriteLine(string.Join(" ", new[] {a, b, c, d}));
    }
}

class Beacon
{
    public System.Action<int, int, int, int> Bar(Spam instance)
    {
        return instance.PrintFourNumbers;
    }
}

class Program
{
    public static void Main()
    {
        var b = new Beacon();
        var s = new Spam();
        b.Bar(s)(1, 2, 3, 4);
    }
}

PrintFourNumbers方法非常难看;如果它接受整数数组,看起来会更好,但是我想让它尽可能接近问题中的示例。你知道吗

相关问题 更多 >

    热门问题