2011-04-28 75 views
13

我怎么会写在C#的等效代码:相当于在C#中的Objective-C代码块

typedef void (^MethodBlock)(int); 

- (void) fooWithBlock:(MethodBlock)block 
{ 
    int a = 5; 
    block(a); 
} 

- (void) regularFoo 
{ 
    [self fooWithBlock:^(int val) 
    { 
     NSLog(@"%d", val); 
    }]; 
} 

回答

16

事情是这样的:

void Foo(Action<int> m) 
{ 
    int a = 5; 
    m(a); 
} 

void RegularFoo() 
{ 
    Foo(val => // Or: Foo(delegate(int val) 
    { 
     Console.WriteLine(val); 
    }); 
} 

Action<T>为代表,它利用一个只有一个参数您指定的类型(在这种情况下,为int),其执行时不返回任何内容。另请参阅常规C# delegate reference

对于这样一个简单的例子,它非常简单。但是,我相信Objective-C和C#中的代表之间存在一些语义/技术差异,这可能超出了这个问题的范围。

+1

只要使用'System.Action '''委托'完成了你。 – pickypg 2011-04-28 19:20:55

+0

谢谢!我在第二部分的第二部分中加上了使用块的调用... – user204884 2011-04-28 19:20:58

+0

对于第二种方法,只需使用匿名委托:'委托(int x){Console.WriteLine(“{0}”,x); ''作为参数。 – pickypg 2011-04-28 19:23:09

1
void fooWithBlock(Action<int> block) 
{ 
    int a = 5; 
    block(a); 
}