C# 委托(delegate)创建和激活

标签 c# delegates

我有两个功能:

double fullFingerPrinting(string location1, string location2, int nGrams)
double AllSubstrings(string location1, string location2, int nGrams)

我想进入一个循环并依次激活每个函数,并且在每个函数之后我还想打印函数的名称,我该怎么做?

最佳答案

  1. 定义您的函数通用的委托(delegate)类型。
  2. 为您的职能创建委托(delegate)集合
  3. 遍历集合,调用每个委托(delegate)并使用 Delegate.Method属性以获取方法名称。

示例(经过编辑以显示非静态函数委托(delegate)):

class Program
{
    delegate double CommonDelegate(string location1, string location2, int nGrams);

    static void Main(string[] args)
    {
        SomeClass foo = new SomeClass();

        var functions = new CommonDelegate[]
        {
            AllSubstrings,
            FullFingerPrinting,
            foo.OtherMethod
        };

        foreach (var function in functions)
        {
            Console.WriteLine("{0} returned {1}",
                function.Method.Name,
                function("foo", "bar", 42)
            );
        }
    }

    static double AllSubstrings(string location1, string location2, int nGrams)
    {
        // ...
        return 1.0;
    }

    static double FullFingerPrinting(string location1, string location2, int nGrams)
    {
        // ...
        return 2.0;
    }
}

class SomeClass
{
    public double OtherMethod(string location1, string location2, int nGrams)
    {
        // ...
        return 3.0;
    }
}

关于C# 委托(delegate)创建和激活,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2927838/

相关文章:

c# - Redis Booksleeve 客户端,ResultCompletionMode.PreserveOrder 不工作

c# - 使用 Parallel 在 C# 中优化文件搜索

c# - 泛型的基本用法

c# - gStreamer-Sharp - 管道无法链接

ios - 类型 MyViewController 不符合协议(protocol) 'STPPaymentContextDelegate'

ios - Objective C - 共享*几乎*相同委托(delegate)方法的类

c# - 想要直观地表示原始信息

c# - 使用委托(delegate) : Invalid token 'void' in class, 结构或接口(interface)成员声明时出错

c# - 在.NET 中,委托(delegate)的内部实现是什么?

ios - Swift4.2 : Why func gameDidEnd(_:) no need to use game parameter but still declare in the function?