4

我想知道,相当于 C# 中的协议和委托。

所以这是我的协议,接口和定义协议的类的实现以及符合协议的类的实现。我想知道这在 c# 中的等价物。请 :)

/******************************************/
// Communicator Protocol
@class Communicator

@protocol CommunicatorDelegate <NSObject>

@required
- (void)communicator:(Communicator *)communicator receivedData:(NSData *)data;
- (void)fetchingFailedWithError:(NSError *)error;

@optional
- (void)anOptinalMethod;

@end

/******************************************/
// Communicator Class

@protocol CommunicatorDelegate;

@interface Communicator : NSObject

@property (weak, nonatomic) id<CommunicatorDelegate> delegate;

@end

/******************************************/
// Communicator Implementation

@implementation

-(void)someMethodThatFail:(NSError *)error;
{
    [self.delegate fetchingFailedWithError:error];
}

- (void)someMethodThatGetData:(NSData *)data;
{
    [self.delegate communicator:self receivedData:data];
}

@end

/******************************************/
// Interface of Some Class that conform with the protocol

#import "Communicator.h"

@interface SomeClass : NSObject <CommunicatorDelegate>

@end

/******************************************/
// Implementation of Some Class that conform with the protocol

- (void)communicator:(Communicator *)communicator receivedData:(NSData *)data;
{
    // Do something
}

- (void)fetchingFailedWithError:(NSError *)error;
{
    // Do something
}
4

1 回答 1

3

协议的直接等价物是接口。由于 obj-c 委托不是一种语言功能,而只是一种设计概念,因此在 C# 中没有等价物。

另外,我强烈建议不要在 obj-c 和 C# 之间重用对象模型。即使使用像您的示例这样的后端代码。语言差异太大。对于像您的示例这样的任务,我会考虑以下替代方案:

  1. 使用 2 个 C# 事件而不是 2 个委托方法。

  2. 使用以下原型作为您的通信方法:void Communicate( Action<YourData> actionToRunOnData )成功时调用操作,失败时抛出异常。仅供参考:Action<YourData> actionToRunOnData相当于void(^)(YourData*)actionToRunOnDataobj-c 中的块。

  3. (我通常更喜欢这个)为您的通信方法使用以下原型:async Task<YourData> Communicate(),并在失败时抛出异常。

PS Funfact:在 C# 术语中,类似的东西Action<YourData> actionToRunOnData被称为“委托”——它与 obj-c 委托没有任何共同之处。

于 2013-10-30T03:32:27.373 回答