简体   繁体   中英

Call an override method in an abstract class

i have a problem. I try to start the override Host method from Program.cs in the abstract class AbstractGenericClass.

public abstract class AbstractGenericClass<T>
{
    protected abstract void Host();

    public static void Start()
    {
        //add additional logic for all classes that use this

        try
        {
            ((AbstractGenericClass<T>) Activator.CreateInstance(typeof(T))).Host();

            Console.WriteLine("Works!");
        }
        catch (Exception ex)
        {
            Console.WriteLine("Don't Works!");
        }
    }
} 

class AnotherClass
{
    public void DoSomething()
    {
        //NOP
    }
}

class Program
    : AbstractGenericClass<AnotherClass>
{
    static void Main(string[] args)
    {
        Program.Start();

        Console.ReadLine();
    }

    protected override void Host()
    {
        Console.WriteLine("Host running...");
    }
}

I add here all sample classes i create for showing what i mean. The line with ((AbstractGenericClass) Activator.CreateInstance(typeof(T))).Host(); crash the program because of InvalidCastException. It must be possible to call the Host method but i have no idea how i could this, if this dont operates.

Have you any other idea how this could operate? Or is this totally wrong what i try?

Replace

((AbstractGenericClass<T>) Activator.CreateInstance(typeof(T))).Host();

with

Host();

Because Host() is an abstract method, Program.Start() will call the implementation of this method in the derived class, so it will execute the implementation of Host() from Program .

You can't cast the result from CreateInstance as AbstractGenericClass because it is of type AnotherClass, which does not derive from AbstractGenericClass and doesn't have a Host method anyway. Sounds like what you want is to get an object of type Program and call Host on that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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