C# 等价于创建实现接口的匿名类 [英] C# equivalent of creating anonymous class that implements an interface

查看:70
本文介绍了C# 等价于创建实现接口的匿名类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始使用 C#,我想找到一个等效的方法.不知道这个叫什么,就简单的用代码给大家看看

I've recently started using C#, and I wanted to find an equivalent method to this. I do not know what this is called, so I will simply show you by code.

使用 Java,我能够创建这样的界面:

With Java, I was able to create an interface like so:

public interface Event {
    public void execute();
}

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

And pass this interface in a method's parameter like so:

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

EDIT :我的问题是关于 TestEvent 类中的 simulatEvent 方法,以及 C# 是否可以执行此类操作.

EDIT : My question is revolved on the simulatEvent method from the TestEvent class, and if such an action is possible with C#.

我想知道是否有一种方法可以使用 C# 执行与此类似的操作(在 simulateEvent 方法中实例化接口)以及实际调用的内容.谢谢!

I wanted to know if there was a way to do something similar to this with C#, (instantiating the interface in the simulateEvent method) and what this is actually called. Thank you!

推荐答案

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

Woof...ok, permit me to generalize a bit:

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

So in Java, you need a way to pass functions around. Java does not inherently support functions as first-class citizens, and this was one reason behind the implementation of anonymous classes - packaged groups of functions that can be declared inline and passed (as interfaces) to methods/other classes that will then call these functions.

在 C# 中,函数是一等公民,可以声明为 DelegatesFunc<>sAction<>s.让我们尝试一个比较(各种):

In C#, functions are first-class citizens, and can be declared as either Delegates, Func<>s, or Action<>s. Let's try a comparison (of sorts):

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

Some sort of Java-y construct (my Java's fairly old, so bear with me):

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) { ... }

在 C# 中的(非常粗略的)等价物是:

The (very rough) equivalent of this in C# would be:

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

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

Now, as others have mentioned, you usually see this pattern on the Java side when dealing with the handling of events - likewise on the C# side:

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

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

Note that we can also give it something with the same "shape":

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

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

But it's also used in Java to define what Threads do, if memory serves (i.e., Runnable) - and we can do this as well in C#:

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

现在,其他东西 - 枚举:

Now, other stuff - enumeration:

public void processEvents(){
    for(Event event : eventList)
        eventList.execute();
}

C# 有同样的想法,只是叫法不同:

C# has the same idea, just called differently:

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

这篇关于C# 等价于创建实现接口的匿名类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆