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

查看:1882
本文介绍了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();
    }
}



修改:我的问题公转从 TestEvent 类的<​​code> 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...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#中,函数是一等公民,可以声明为代表 Func键<> S 动作<> 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天全站免登陆