How to instantiate a class with abstract methods in C #

2

In Java we can implement abstract methods when instantiating a given class

Thread threadA = new Thread(new Runnable(){
        public void run(){
            for(int i =0; i<2; i++){
                System.out.println("This is thread : " + Thread.currentThread().getName());
            }
        }
    }, "Thread A");

I would like to know if this is possible in C #, implement an abstract method at the last minute, and if possible I would like an example

    
asked by anonymous 02.09.2014 / 18:31

2 answers

8

It is possible, you only have to create the declaration of the method abstractly and then in the class you want to add the implementation to use the override.

public abstract class MinhaClasseBase
{
    public abstract void MeuMetodo(string parametro);
}

public class MinhaClasse : MinhaClasseBase
{
    public override void MeuMetodo(string parametro)
    {
        Console.Write(parametro);
    }
}

If your intention is to create anonymous methods to start a thread, then you could do this:

var thread = new Thread(t =>
{

    for(int i = 0; i < 2; i++)
        Console.WriteLine("Dentro da thread. [{0}]", i);

}) { IsBackground = true };
thread.Start();
    
02.09.2014 / 18:41
1

Yes, through an object called Action Delegate :

  

link

For example:

class Teste
{
    public static void MinhaAcao<T>(T numero)
    {
        Console.WriteLine("Numero = " + numero);
    }

    public static Delegate CriarAcao(Type type)
    {
        var methodInfo = typeof (Teste).GetMethod("MinhaAcao").MakeGenericMethod(type);
        var actionT = typeof (Action<>).MakeGenericType(type);
        return Delegate.CreateDelegate(actionT, methodInfo);
    }

    static void Main(string[] args)
    {
        CriarAcao(typeof (int)).DynamicInvoke(5);
        Console.ReadLine();
    }
}
    
02.09.2014 / 18:39