Override abstract method when instantiating in C #

In java, we can override or implement abstract methods when creating an instance as follows:

AbstractClass test =new AbstractClass() 
{
    public void AbstractMethod(string i) {

    }
    public void AbstractMethod2(string i) {

    }
};

Is this possible in C #? if so what equivalent code

thank

+5
source share
3 answers

This Java function is called an “anonymous class,” not “overriding a method at instantiation”. C # does not have the same function.

C # took a different route — instead of providing convenient syntax for creating subclasses, it expanded its delegation functions by providing anonymous delegates and lambdas . Lambdas allows you to embed code snippets.

+8

- :

public class BaseClass {

    public BaseClass(Action<string> abs1 = null, Action<string> abs2 = null){
       AbstractMethod1 = abs1 ?? s=>{};
       AbstractMethod2 = abs2 ?? s=>{};
    }

    public Action<string> AbstractMethod1 {get; private set;}
    public Action<string> AbstractMethod2 {get; private set;}
}

, :

new BaseClass( s=> Console.WriteLine(s), s=> Console.WriteLine(s));

, ( ). "". .

+2

I don’t know Java, but it "smells" like Anonymous types in C#.

For example, you can write something like:

 var myNewType = new { 
                       Name = "Charles", 
                       Surname="Dickens", 
                       Age = 55 
                      };
0
source

All Articles