C # Action Delegate VS JAVA action Interface function
1, C#:action
Encapsulates a method that does not have parameters and does not return a value.
Constructing entity class classes
1 usingSystem;2 3 namespaceactionsdelegate4 {5 Public className6 {7 Private stringinstancename;8 9 PublicName (stringname)Ten { One This. InstanceName =name; A } - - Public voidDisplaytoconsole () the { -Console.WriteLine ( This. InstanceName); - } - } +}
1 usingSystem;2 3 namespaceactionsdelegate4 {5 class Program6 {7 Static voidMain (string[] args)8 {9Name name =NewName ("Jeff");TenAction action =name. Displaytoconsole; One action (); A Console.readkey (); - } - } the}
Invoke the Action delegate
using System; namespace actionsdelegate{ class program { staticvoid Main ( string [] args) { new Name ("Jeff"); = name. Displaytoconsole; Action (); Console.readkey (); }}}
Execution result: output a Jeff string
2. JAVA:
Java does not have a standard action interface, and some articles say you can replace it with runnable, but Runnable is run on the thread, and we construct a Java interface function here
1 @FunctionalInterface 2 Public Interface Action {3 void 4 default action Andthen (action after) {5 Objects.requirenonnull (after); 6 return (), {accept (); After.accept ();}; 7 }8 }
Constructing entity classes
1 Public className {2 3 PrivateString instancename;4 5 Publicname (String name) {6 This. InstanceName =name;7 }8 9 Public voidDisplaytoconsole () {TenSystem.out.println ( This. InstanceName); One } A}
Call the Action interface function
1 Public class 2public staticvoid main (String args[]) {3 name name=new name ("Jeff"); 4 Action action= (),name. Displaytoconsole (); 5 6} 7}
Execution result: output a Jeff string
Summarize:
So the Java interface function is basically the same as the purpose that C # delegates achieve
JAVA Functional interface and C # delegate correspondence relationship (I.)