等效于 C# 中的协议和委托

本文关键字:协议 | 更新日期: 2023-09-27 18:37:20

我想知道,相当于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
}

等效于 C# 中的协议和委托

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

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

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

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

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

P.S. Funfact:在C#术语中,像Action<YourData> actionToRunOnData这样的东西被称为"委托"——这与obj-c委托没有任何共同之处。