调用inherit和base方法

时间:2016-10-14 06:19:57

标签: c# class inheritance

我有2个班级

public class A
{
    public A(string N)
    {
        Name = N;
    }
    public string Name { get; set; }

    public void GetName()
    {
        Console.Write(Name);
    }
}

public class B : A
{
    public B(string N) : base(N)
    {
    }

    public new void GetName()
    {
        Console.Write(new string(Name.Reverse().ToArray()));
    }
}

我创建了一个新对象B,我想从GetName AGetName B来呼叫B foo = new B("foo"); foo.GetName(); // output "oof"

"foooof"

预期输出public new void GetName() : base

我已经尝试了AJAX但是没有编译

3 个答案:

答案 0 :(得分:2)

使用override并从重写方法调用基类'方法:

public class A
{
    public virtual void GetName()
    {
        Console.Write(Name);
    }
}

public class B : A
{
    public override void GetName()
    {
        base.GetName();
        Console.Write(new string(Name.Reverse().ToArray()));
    }
}

virtual关键字用于修改方法并允许在派生类中重写它,而new修饰符隐藏基类方法。通过调用base.GetName();您正在执行基本方法BTW,这就是为什么您在此处使用newoverride关键字没有区别,尽管我建议使用override

参考文献:

virtual (C# Reference)

Knowing When to Use Override and New Keywords

答案 1 :(得分:2)

要获得所需的输出,您需要在base GetName()的{​​{1}}方法中调用GetName()方法。像这样举例如:

Class B

这将放出public class A { public A(string N) { Name = N; } public string Name { get; set; } public void GetName() { Console.Write(Name); } } public class B : A { public B(string N) : base(N) { } public new void GetName() { base.GetName(); Console.Write(new string(Name.Reverse().ToArray())); } }

答案 2 :(得分:0)

public class A
{
    public A(string N)
    {
        Name = N;
    }
    public string Name { get; set; }

    public virtual void GetName()
    {
        Console.Write(Name);
    }
}

public class B : A
{
    public B(string N) : base(N)
    {
    }

    public override void GetName()
    {
        base.GetName();
        Console.Write(new string(Name.Reverse().ToArray()));
    }
}

根据您的选择使用覆盖或新建。 喜欢处理这些场景。

            A foo = new B("foo");
            foo.GetName();

            A foo = new A("foo");
            foo.GetName();

            B foo = new B("foo");
            foo.GetName();

msdn link会给你清晰的图片。