简体   繁体   English

在抽象类中调用重写方法

[英]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. 我尝试从抽象类AbstractGenericClass中的Program.cs启动重写Host方法。

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(); 具有((AbstractGenericClass)Activator.CreateInstance(typeof(T)))。Host();的行 crash the program because of InvalidCastException. 由于InvalidCastException而使程序崩溃。 It must be possible to call the Host method but i have no idea how i could this, if this dont operates. 一定可以调用Host方法,但是我不知道如何操作(如果此操作不起作用)。

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 . 因为Host()是抽象方法,所以Program.Start()将在派生类中调用此方法的实现,因此它将从Program执行Host()的实现。

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. 您不能将CreateInstance的结果强制转换为AbstractGenericClass,因为它的类型为AnotherClass,它不是从AbstractGenericClass派生的,并且也没有Host方法。 Sounds like what you want is to get an object of type Program and call Host on that. 听起来您想要的是获取一个Program类型的对象并在其上调用Host。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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