【问题标题】:c# passing inline interface like delegate methodc# 像委托方法一样传递内联接口
【发布时间】: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#不支持实例化interfaceneither does Java
  • ...但是,如果你定义一个继承自 Interaction 的类 Foo,你可以有一个 Foo (Action<string> onSuccess, Action<string> onError) 构造函数
  • 另一个不太可重用的选项是在GetData 中添加2 个Action<string> 参数并在Main 中使用lambdas
  • ...还有一个选择是使用Microsoft Fakes framework's stubs

标签: c# interface delegates


【解决方案1】:

重新设计的一种方法是接受两个Action<string> 参数:

void GetData(Action<string> onSuccess, Action<string> onFailure)
{
    //someCode
    onSuccess("foo");
}

void Main()
{
    GetData(onSuccess: result => {
        // success part...
    }, onFailure: error => {
        // failure part
    });
}

另一种方法是保留IInteraction接口:

public interface IInteraction
{
    void OnSuccess(String result);
    void OnFailure(String error);
}

void GetData(IInteraction interaction)
{
    //someCode
    interaction.OnSuccess("foo");
}

但是有一个具体的类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); }
}

这样,方法的调用者可以选择传入onSuccessonFailure“inline”:

GetData(new GenericInteraction(onSuccess: result => {
    // success part...
}, onFailure: error => {
    // failure part
}));

或者传递其他实现IInteraction的东西:

GetData(someOtherInteractionICreated);

这更接近于您在 Java 中可以做的事情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-05
    • 1970-01-01
    • 2015-01-30
    • 1970-01-01
    • 2017-02-28
    • 1970-01-01
    相关资源
    最近更新 更多