-1

This question already has an answer here:

I have a class that has an interface in it like so:

 public class hcmTerminal {

    ... Code

    public interface onDataReceived {
        void isCompleted(bool done);
    }

}

inside this class I I have the public property:

public onDataReceived mDataReceived;

then I have a function to set the delegate:

public void setDataReceived(onDataReceived dataReceived) { mDataReceived = dataReceived; }

Inside the hcmTerminal class I am am calling the delegate :

mDataReceived.isCompleted(true);

But I can't figure out the syntax to actually get when that delegate gets called, In java I can go:

myTerminal.setDataReceived(new hcmTerminal.onDataReceived(){

    @Override
    public void isCompleted(boolean done){

        ... Code

    }

});

But if I try that in C# I get:

Cannot create an instance of the abstract or interface 'hcmTerminal.onDataReceived'

I haven't had to create a interface in C# before. this code is coming from how I implemented it in Java.


  • I would very strongly urge you to follow the naming conventions of .NET when writing C#, and Java when writing Java. Currently you're violating both. - Jon Skeet
  • Just so you know a method of an interface is not a delegate. C# has a delegate type it uses instead of interfaces. But if you use an interface you have to create a class that implements that interface. - juharr
  • As for your interface - is there any reason you're creating an interface rather than a delegate? You talk about a delegate, but you're declaring an interface... - Jon Skeet
  • Shouldn't you just use events instead? msdn.microsoft.com/en-us/library/aa645739(v=vs.71).aspx - Pawel Gradecki
  • I'm not sure I've found the best duplicate, more - bing.com/… - Alexei Levenkov

2 답변


2

By using events you can accomplish that by

 class HcmTerminal {
      public event Action<bool> OnDataReceived;

      public void Launch()
      {
           OnDataReceived?.Invoke(true /*or false*/);
      }

 }

You can then do:

var myTerminal = new HcmTerminal();
myTerminal.OnDataReceived += (isCompleted) => {};


2

Define a class implementing the interface:

class MyDataReceived : hcmTerminal.onDataReceived {
    public void isCompleted(bool done) {
        Console.WriteLine("call to isCompleted. done={0}", done);
    }
}

Now you can call myTerminal.setDataReceived(new MyDataReceived())

However, this is a Java solution coded in C#, not a "native" C# solution. A better approach is to define a delegate in place of an interface:

public class HcmTerminal {
    ... Code
    public delegate void OnDataReceived(bool done);
}

This would let you use multiple C# features for supplying delegate implementation, such as providing a method name, supplying an anonymous delegate, or using a lambda:

myTerminal.setDataReceived((done) => {
    Console.WriteLine("call to isCompleted. done={0}", done);
});

Linked


Related

Latest