[英]c# passing inline interface like delegate method
i',m using this syntax in java: 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
}
})
}
i'm new at c# coding.我是 c# 编码的新手。 how can i implement that structure in c#?
我如何在 c# 中实现该结构? does c# support inline instance interface as java?
c# 是否支持内联实例接口为 java?
One way to redesign this is to accept two Action<string>
parameters:重新设计它的一种方法是接受两个
Action<string>
参数:
void GetData(Action<string> onSuccess, Action<string> onFailure)
{
//someCode
onSuccess("foo");
}
void Main()
{
GetData(onSuccess: result => {
// success part...
}, onFailure: error => {
// failure part
});
}
Another way is to keep the IInteraction
interface:另一种方法是保留
IInteraction
接口:
public interface IInteraction
{
void OnSuccess(String result);
void OnFailure(String error);
}
void GetData(IInteraction interaction)
{
//someCode
interaction.OnSuccess("foo");
}
But have a concrete class GenericInteraction
that implements IInteraction
:但是有一个实现
IInteraction
的具体 class GenericInteraction
:
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); }
}
This way, the caller of the method can choose to either pass in onSuccess
and onFailure
"inline":这样,方法的调用者可以选择传入
onSuccess
和onFailure
"inline":
GetData(new GenericInteraction(onSuccess: result => {
// success part...
}, onFailure: error => {
// failure part
}));
Or pass something else that implements IInteraction
:或者传递其他实现
IInteraction
的东西:
GetData(someOtherInteractionICreated);
Which is closer to what you could do in Java.这更接近您在 Java 中可以做的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.