本文介绍了抽象类细节..............................的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

using System;
abstract class test
{
         public abstract void hello();
    public test()
{
    Console.WriteLine("base class");
    hello();
}


}

 class test1 : test
{


    public override void hello()
    {



        Console.WriteLine("hii i m defined  in derived class");


    }

    public static void Main()
    {
        new test1();
        Console.WriteLine("i m in main ");
        Console.ReadLine();
    }
}







请我知道如何上面程序中的派生类方法调用

。背景机制




please i want to aware from the fact how the derive class method call in above program
. background mechanism

推荐答案

new test1();

test1 类派生自 test 类,所以 test 构造函数(因为 test1 类在基类之前不能依赖它的基类内的任何东西构造函数完成):

The test1 class is derived from the test class, so the test constructor is called first (as the test1 class cannot rely on anything within it''s base class until the base class constructor is completed):

public test()
    {
    Console.WriteLine("base class");
    hello();
    }

这会将一行写入控制台,并调用 test.hello 方法。

test hello 方法是抽象的,编译器只查找派生类中的实现并调用: test1.hello

This writes a line to the console, and calls the test.hello method.
Since the test class hello method is abstract, the compiler only looks for an implementation in the derived class and calls that: test1.hello

public override void hello()
    {
    Console.WriteLine("hii i m defined  in derived class");
    }

哪个写另一行。



这是合法的,允许的,但这可能是一个糟糕的主意,因为在派生类实例中的方法之前尚未调用 test1 类构造函数 - 这可能意味着在首次调用该方法时未初始化派生类项。如果可能的话,我不会这样做,如果必须的话,我会在抽象方法声明的评论中想要一些严厉的警告!

Which writes the other line.

This is all legal and allowed, but it''s probably a poor idea, as the test1 class constructor has not been called before a method in the derived class instance is - which may mean that derived class items are not initialized when the method is first called. I wouldn''t do it if at all possible, and if I had to, I''d want some severe warnings in the comments for the abstract method declaration!


这篇关于抽象类细节..............................的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-16 23:42