C#: Creating an instance of an abstract class without defining new class

前端 未结 9 787
眼角桃花
眼角桃花 2020-12-29 04:25

I know it can be done in Java, as I have used this technique quite extensively in the past. An example in Java would be shown below. (Additional question. What is this techn

9条回答
  •  甜味超标
    2020-12-29 05:11

    Since your class represents only an action, you can use a delegate in your case, there is an existing delegate :

    public delegate void Action();
    

    This is the exact equivalent of your class.

    And the déclaration of your anonymous class is even cleaner :

    Action action = () => Console.WriteLine("Hello world");
    action(); // invoke
    

    you can even use closure :

    public void Hello(string name)
    {
      Action action = () => Console.WriteLine("Hello " + name);
      action(); // will call the above lambda !
    }
    

提交回复
热议问题