2010-05-28 108 views
1

我有两个功能:C#delegete创建和激活

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

我想去一个循环,并反过来激活每个功能,每个功能后,我也想打印函数的名称,我怎样才能做到这一点?

回答

5
  1. 定义通用于您的函数的委托类型。
  2. 为您的功能创建一个代表集合
  3. 循环访问集合,调用每个代理并使用Delegate.Method属性获取方法名称。

例(编辑显示非静态函数代表):

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; 
    } 
} 
+0

坦克!!你帮了很多忙! – aharon 2010-05-28 09:33:28

+0

函数必须是静态的吗?多数民众赞成在遗弃我的一切,因为这个功能使用没有静态功能... – aharon 2010-05-28 09:39:56

+0

@aharont:不,该函数可以是一个对象的成员函数。我更新了我的答案,包括一个例子。 – 2010-05-28 10:03:52

0

不知道这是否会有所帮助,但我做了一个帖子delegates and events that fire,您可以使用一个委派,并将其连接到一个事件,如果您调用该事件,它会触发所有与该事件相关的代理,因此不需要循环。