c#像委托方法一样传递内联接口
我在java中使用以下语法:c#像委托方法一样传递内联接口,c#,interface,delegates,C#,Interface,Delegates,我在java中使用以下语法: public interface Interaction { void onSuccess(String result); void onFailure(String error); } void getData(Interaction interaction) { //someCode interaction.onSuccess("foo"); }
public interface Interaction
{
void onSuccess(String result);
void onFailure(String error);
}
void getData(Interaction interaction)
{
//someCode
interaction.onSuccess("foo");
}
void main()
{
getData(new Interaction()
{
@override
void onSuccess(String result)
{
//here is sucess part
}
@override
void onFailure(String error)
{
//here is failure part
}
})
}
我是c#coding的新手。如何在c#中实现该结构?
c#是否像java一样支持内联实例接口 重新设计的一种方法是接受两个
操作
参数:
void GetData(Action<string> onSuccess, Action<string> onFailure)
{
//someCode
onSuccess("foo");
}
void Main()
{
GetData(onSuccess: result => {
// success part...
}, onFailure: error => {
// failure part
});
}
但是有一个具体的类GenericInteraction
,它实现了IInteraction
:
class GenericInteraction : IInteraction {
private Action<string> onSuccess;
private Action<string> onFailure;
public GenericInteraction(Action<string> onSuccess, Action<string> onFailure) {
this.onSuccess = onSuccess;
this.onFailure = onFailure;
}
public void OnSuccess(String result) { onSuccess(result); }
public void OnFailure(String error) { onFailure(error); }
}
GetData(someOtherInteractionICreated);
或者传递实现i交互的其他内容
:
class GenericInteraction : IInteraction {
private Action<string> onSuccess;
private Action<string> onFailure;
public GenericInteraction(Action<string> onSuccess, Action<string> onFailure) {
this.onSuccess = onSuccess;
this.onFailure = onFailure;
}
public void OnSuccess(String result) { onSuccess(result); }
public void OnFailure(String error) { onFailure(error); }
}
GetData(someOtherInteractionICreated);
这更接近于您在Java中所能做的。不,它不是。你需要重新设计你的API。首先,C不支持实例化接口……但是,如果你定义一个继承自交互的类
Foo
,你可以有一个Foo(Action onSuccess,Action onError)
构造函数或其他可重用性较差的类,选项是使用2个Action
参数来GetData
并在Main
中使用lambdas…还有一个选项是使用