Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
c#像委托方法一样传递内联接口_C#_Interface_Delegates - Fatal编程技术网

c#像委托方法一样传递内联接口

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"); }

我在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#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…还有一个选项是使用