How to instantiate a class with abstract methods in C#

Asked

Viewed 264 times

2

In java we can implement abstract methods by instantiating a certain 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 wonder if this is possible in C#, implementing an abstract method at the last minute, and if possible would like an example

2 answers

8

It is possible yes, you just need to create the method declaration abstractly and then in the class you want to add the implementation 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 mount it like this:

var thread = new Thread(t =>
{

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

}) { IsBackground = true };
thread.Start();

1

Yes, through an object called Action Delegate:

http://msdn.microsoft.com/en-us/library/system.action.aspx

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.