JAVA 函数式接口与c#委托对应关系(一)

C# Action委托 VS JAVA Action 接口函数

1、c#:Action

封装一个方法,该方法不具有参数并且不返回值。

构造实体类类

 1 using System;
 2 
 3 namespace ActionsDelegate
 4 {
 5     public class Name
 6     {
 7         private string instanceName;
 8 
 9         public Name(string name)
10         {
11             this.instanceName = name;
12         }
13 
14         public void DisplayToConsole()
15         {
16             Console.WriteLine(this.instanceName);
17         }  
18     }
19 }

 

 1 using System;
 2 
 3 namespace ActionsDelegate
 4 {
 5     class Program
 6     {
 7         static void Main(string[] args)
 8         {
 9             Name name = new Name("Jeff");
10             Action action = name.DisplayToConsole;
11             action(); 
12             Console.ReadKey();
13         } 
14     }
15 }

调用Action委托

using System;

namespace ActionsDelegate
{
    class Program
    {
        static void Main(string[] args)
        {
            Name name = new Name("Jeff");
            Action action = name.DisplayToConsole;
            action(); 
            Console.ReadKey();
        } 
    }
}

执行结果:输出一个Jeff字符串

 

2、JAVA:

java没有标准的Action接口,有些文章说可以用Runnable替代,但是Runnable是的run是运行在线程之上的,我们在这构造一个JAVA的接口函数

1 @FunctionalInterface
2 public interface Action {
3     void accept(); 
4     default Action andThen(Action after) {
5         Objects.requireNonNull(after);
6         return () -> { accept(); after.accept(); };
7     }
8 }

 

构造实体类

 1 public class Name {
 2 
 3     private String instanceName;
 4 
 5     public Name(String name) {
 6         this.instanceName = name;
 7     }
 8 
 9     public void DisplayToConsole() {
10         System.out.println(this.instanceName);
11     }
12 }

调用Action接口函数

1 public  class TestFunction { 
2     public static void main(String args[]){
3         Name name=new Name("Jeff");
4         Action action=()->name.DisplayToConsole();
5         action.accept(); 
6     }
7 }

执行结果:输出一个Jeff字符串

总结:

这样JAVA接口函数与C#委托达到的目的基本一样

 

posted @ 2015-12-13 12:08  cnkker.com  阅读(1653)  评论(0编辑  收藏  举报