C# C语言中协议和委托的等价性#
我想知道,C#中协议和委托的等价物 这就是我的协议,定义协议的类的接口和实现,以及符合协议的类的实现。我想知道c#中的等价物。请:)C# C语言中协议和委托的等价性#,c#,ios,.net,objective-c,winforms,C#,Ios,.net,Objective C,Winforms,我想知道,C#中协议和委托的等价物 这就是我的协议,定义协议的类的接口和实现,以及符合协议的类的实现。我想知道c#中的等价物。请:) /******************************************/ //通信器协议 @类通信器 @协议通信或网关 @必需的 -(无效)通信器:(通信器*)通信器接收数据:(NSData*)数据; -(void)fetchingFailedWithError:(n错误*)错误; @可选的 -(无效)选择方法; @结束 /************
/******************************************/
//通信器协议
@类通信器
@协议通信或网关
@必需的
-(无效)通信器:(通信器*)通信器接收数据:(NSData*)数据;
-(void)fetchingFailedWithError:(n错误*)错误;
@可选的
-(无效)选择方法;
@结束
/******************************************/
//通信器类
@协议通信或网关;
@接口通信器:NSObject
@属性(弱、非原子)id委托;
@结束
/******************************************/
//通信器实现
@实施
-(void)失败的某些方法:(n错误*)错误;
{
[self.delegate fetchingFailedWithError:错误];
}
-(void)获取数据的某些方法:(NSData*)数据;
{
[self.delegate communicator:self receivedData:data];
}
@结束
/******************************************/
//符合协议的某个类的接口
#导入“Communicator.h”
@接口类:NSObject
@结束
/******************************************/
//一些符合协议的类的实现
-(无效)通信器:(通信器*)通信器接收数据:(NSData*)数据;
{
//做点什么
}
-(void)fetchingFailedWithError:(n错误*)错误;
{
//做点什么
}
协议的直接等价物是接口。
由于obj-c委托不是一种语言特性,而仅仅是一种设计概念,因此在c#中没有等价物
另外,我强烈建议不要在obj-c和c#之间重用对象模型。即使使用像您的示例那样的后端代码。语言太不一样了。
对于像你的例子的任务,我会在下列选项之间考虑:
void Communicate(Action ActionToRunnda)
,成功时调用操作,失败时抛出异常。仅供参考:Action-actiontorunadata
相当于obj-c中的void(^)(YourData*)actiontorunadata
块async Task Communicate()
,失败时抛出异常p.S.Funfact:在C#术语中,像Action ActionToRunnda这样的东西被称为“委托”——它与obj-C委托没有任何共同之处。对于不熟悉Objective-C的人来说,该语言中协议和委托的目的是什么?所以这有点像Objective 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
}