【发布时间】:2020-05-29 07:41:22
【问题描述】:
i',m 在java中使用这个语法:
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# 编码的新手。我如何在 C# 中实现该结构? c# 支持内联实例接口作为 java 吗?
【问题讨论】:
-
不,它没有。您需要重新设计 API。
-
首先C#不支持实例化interface和neither does Java
-
...但是,如果你定义一个继承自
Interaction的类Foo,你可以有一个Foo (Action<string> onSuccess, Action<string> onError)构造函数 -
另一个不太可重用的选项是在
GetData中添加2 个Action<string>参数并在Main中使用lambdas -
...还有一个选择是使用Microsoft Fakes framework's stubs