简体   繁体   English

C#相当于创建实现接口的匿名类

[英]C# equivalent of creating anonymous class that implements an interface

I've recently started using C#, and I wanted to find an equivalent method to this. 我最近开始使用C#,我想找到一个等效的方法。 I do not know what this is called, so I will simply show you by code. 我不知道这叫什么,所以我只会通过代码向您展示。

With Java, I was able to create an interface like so: 使用Java,我能够创建如下界面:

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 : My question is revolved on the simulatEvent method from the TestEvent class, and if such an action is possible with C#. 编辑 :我的问题是来自TestEvent类的simulatEvent方法,如果C#可以执行此类操作。

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. 我想知道是否有办法用C#做一些类似的事情(在simulateEvent方法中实例化接口)以及实际调用它的方法。 Thank you! 谢谢!

Woof...ok, permit me to generalize a bit: Woof ......好的,请允许我概括一下:

So in Java, you need a way to pass functions around. 所以在Java中,你需要一种传递函数的方法。 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. Java本身并不支持作为一等公民的功能,这是实现匿名类的一个原因 - 打包的函数组,可以内联声明并传递给接口,然后传递给方法/其他类,然后调用这些函数。

In C#, functions are first-class citizens, and can be declared as either Delegates , Func<>s , or Action<>s . 在C#中,函数是一等公民,可以声明为DelegatesFunc<>sAction<>s Let's try a comparison (of sorts): 让我们尝试比较(各种):

Some sort of Java-y construct (my Java's fairly old, so bear with me): 某种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) { ... }

The (very rough) equivalent of this in C# would be: C#中的(非常粗略)相当于:

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

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: 现在,正如其他人所提到的,在处理事件时,您通常会在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();
 }

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

But it's also used in Java to define what Threads do, if memory serves (ie, Runnable ) - and we can do this as well in C#: 但它也用于Java来定义Threads做什么,如果内存服务(即Runnable ) - 我们也可以在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# has the same idea, just called differently: 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();
    }
}

EDIT: It looks like your question is about anonymous interface implementations instead of events. 编辑:看起来你的问题是关于匿名接口实现而不是事件。 You can use the built-in Action delegate type instead of your Event interface. 您可以使用内置的Action委托类型而不是Event接口。

You can then Action instances using lambda expressions. 然后,您可以使用lambda表达式的Action实例。 Your code would look like: 您的代码如下所示:

public class TestEvent
{
    List<Action> eventList = new List<Action>();

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

    public void simulateEvent(){
        addEvent(() => {
        });
    }

    public void processEvents(){
        for(Action event : eventList)
            event();
    }
}

You can use the delegate syntax instead of using () => { .. .} ie delegate() { ... } in simulateEvent . 您可以使用delegate语法而不是在simulateEvent中使用() => { .. .} ie delegate() { ... }

C# doesn't support anonymous interface implementations, so if your interface has multiple methods then you'll have to define a concrete class somewhere. C#不支持匿名接口实现,因此如果您的接口有多个方法,那么您必须在某处定义一个具体的类。 Depending on the usage you could just have this class contain delegate properties which you can supply on creation eg 根据用途,您可以让此类包含您可以在创建时提供的委托属性,例如

public class Delegates
{
    public Action Event { get; set; }
    public Func<string> GetValue { get; set; }
}

You can then create it like: 然后你可以创建它:

var anon = new Delegates
{
    Event = () => { ... },
    GetValue = () => "Value"
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM