C#等效于创建实现接口的匿名类

use*_*034 5 c# java interface anonymous-class

我最近开始使用C#,并且我想找到与此等效的方法。我不知道这叫什么,所以我将简单地通过代码向您展示。

使用Java,我能够创建如下接口:

public interface Event {
    public void execute();
}
Run Code Online (Sandbox Code Playgroud)

并在方法的参数中传递此接口,如下所示:

public class TestEvent {
    ArrayList<Event> eventList = new ArrayList<Event>();

    public void addEvent(Event event){
        eventList.add(event);
    }

    public void simulateEvent(){
        addEvent(new Event() {
            public void execute(){
                //functionality
            }
        } );
    }

    public void processEvents(){
        for(Event event : eventList)
            eventList.execute();
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:我的问题是关于类中的simulatEvent方法的TestEvent,如果使用C#可以进行这样的操作。

我想知道是否有一种方法可以使用C#执行类似的操作(实例化simulateEvent方法中的接口),以及这实际上是什么。谢谢!

Jer*_*all 5

哇...好吧,请允许我概括一下:

因此,在Java中,您需要一种方法来传递函数。Java本质上不支持将函数作为一等公民,这是实现匿名类的背后原因之一-打包的函数组可以内联声明并(作为接口)传递给方法/其他类,然后再调用这些函数。

在C#中,函数是一等公民,可以声明为DelegatesFunc<>sAction<>s。让我们尝试一下比较:

某种Java-y构造(我的Java相当老,请耐心等待):

public interface IDoSomething {
    public int Return42();
    public bool AmIPrettyOrNot(string name);
    public void Foo();
} 

public void Main(String[] args) {
    DoStuff(new IDoSomething() {
        public int Return42() { return 42; }
        public bool AmIPrettyOrNot(string name) { return name == "jerkimball"; }
        public bool Foo(int x) { ... }
    });
}

public void DoStuff(IDoSomething something) { ... }
Run Code Online (Sandbox Code Playgroud)

C#中的(非常粗糙)等效项为:

public void Main(string[] args)
{
    Func<int> returns42 = () => 42;
    Func<string,bool> amIPretty = name => name == "jerkimball";
    Action<int> foo = x => {};
}
Run Code Online (Sandbox Code Playgroud)

现在,就像其他人提到的那样,在处理事件时,通常会在Java端看到这种模式-同样在C#端:

 public class Foo 
 {
     // define the shape of our event handler
     public delegate void HandlerForBarEvent(object sender, EventArgs args);
     // declare our event
     public event HandlerForBarEvent BarEvent;

     public void CallBar()
     {
         // omitted: check for null or set a default handler
         BarEvent(this, new EventArgs());
     }
 }    

 public void Main(string[] args)
 {
      var foo = new Foo();
      // declare the handler inline using lambda syntax
      foo.BarEvent += (sender, args) => 
      {
           // do something with sender/args
      }
      foo.CallBar();
 }
Run Code Online (Sandbox Code Playgroud)

注意,我们也可以给它一些具有相同“形状”的东西:

 public void MyHandler(object sender, EventArgs args)
 {
     // do stuff
 }
 public void Main(string[] args)
 {
      var foo = new Foo();
      // that method above is the same "shape" as HandlerForBarEvent
      foo.BarEvent += MyHandler;
      foo.CallBar();
 }
Run Code Online (Sandbox Code Playgroud)

但是在Java中,如果内存(即Runnable)起作用,它也可以用来定义线程的功能-我们也可以在C#中做到这一点:

var thread = new Thread((Action)(() => 
     {
         // I'm the threads "run" method!
     });
thread.Start();
Run Code Online (Sandbox Code Playgroud)

现在,其他内容-枚举:

public void processEvents(){
    for(Event event : eventList)
        eventList.execute();
}
Run Code Online (Sandbox Code Playgroud)

C#的想法相同,只是调用方式不同:

public void processEvents()
{
    // edit: derp, 'event' is a keyword, so I'm
    // renaming this, since I won't get into why
    // you could also use @event...
    foreach(var evt in eventList)
    {
        evt.Execute();
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @Romoku 哦,你只是在挑剔:) - 是的,你是对的;不要问我有多少次尝试在 monadic 声明期间击败 C# 编译器类型推断提交... (2认同)