我想知道,相当于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
}
答案 0 :(得分:3)
协议的直接等价物是接口。 由于obj-c委托不是一种语言特征而只是一种设计概念,因此在C#中没有对应的代表。
另外,我强烈建议不要在obj-c和C#之间重用对象模型。即使使用像您的示例的后端代码。语言太不同了。 对于像你的例子这样的任务,我会考虑以下几种选择:
使用2个C#的事件而不是2个委托方法。
使用以下原型作为通信方法:void Communicate( Action<YourData> actionToRunOnData )
,调用成功操作,并在失败时抛出异常。仅供参考:Action<YourData> actionToRunOnData
相当于obj-c中的void(^)(YourData*)actionToRunOnData
块。
(我通常更喜欢这个)使用以下原型进行通信方法:async Task<YourData> Communicate()
,并在失败时抛出异常。
P.S。 Funfact:在C#术语中,像Action<YourData> actionToRunOnData
这样的东西被称为“委托” - 它与obj-c代表没有任何共同之处。