如何为儿童定义访问器?

时间:2018-11-07 16:09:26

标签: c# oop inheritance

我有3个班级:

public interface IParent
{
    String World { get; }
}

public class Parent : IParent
{
    public String World;
    {
        get
        {
            return "Hello " + this.World;
        }
    }
}

public class Children : Parent
{
    public String World = "World";
}

我应该如何使用Parent的{​​{1}}属性调用World的get访问器?

4 个答案:

答案 0 :(得分:2)

您可以为后缀使用第二个属性,并将其设置为虚拟,以允许后代将其覆盖

public class Parent : IParent
{
    protected virtual string Suffix => "World";

    public String World => "Hello " + Suffix;
}

public class Children : Parent
{
    protected override string Suffix => "Again";
}

父母将显示“ Hello World”,孩子将显示“ Hello Again”。这仅适用于运行时类型。静态(即编译时间)类型无关紧要。

Parent p = new Children();
Console.WriteLine(p.World); // Displays "Hello Again"!

此处,p的静态类型为Parent。运行时类型为Children。这种行为称为Polymorphism (C# Programming Guide)

真正的Parent无法知道后缀“ Again”。

答案 1 :(得分:1)

您可以使用其他将是虚拟的私有字段,因此可以在子对象中覆盖它。

尝试一下:

public interface IParent
{
    string HelloWorld { get; }
}

public class Parent : IParent
{
    protected virtual string World { get; }

    public string HelloWorld
    {
        get
        {
            return "Hello " + World;
        }
    }
}

public class Children : Parent
{
    protected override string World { get; } = "World";
}

或者您也可以通过构造函数传递一个字符串,然后可以在运行时设置值。

public interface IParent
{
    string HelloWorld { get; }
}

public class Parent : IParent
{
    private readonly string world;

    public Parent(string world)
    {
        this.world = world;
    }

    public string HelloWorld
    {
        get
        {
            return "Hello " + world;
        }
    }
}

public class Children : Parent
{
    public Children(string world) : base(world)
    {
    }
}

像这样使用它:

var children = new Children("World");
Console.WriteLine(children.HelloWorld);

答案 2 :(得分:0)

这是回到前面。

取决于继承类,包括来自覆盖 (如果需要) 的基类行为。子类override是基本行为,但是通过base关键字可以钩接到基类。

因此:

public interface IParent
{
    String World { get; }
}

public class Parent : IParent
{
    public virtual String World
    {
        get
        {
            return "Hello";
        }
    }
}

public class Children : Parent
{
    public override String World
    {
        get
        {
            return base.World + " World!";
        }
    }
}

答案 3 :(得分:0)

该属性已经是父级的一部分。但是,您需要一个受保护的set函数...像这样在构造函数中对其进行设置:

public interface IParent
{
    String World { get; }
}

public class Parent : IParent
{
    public String World { get; protected set; }
    public Parent() { World = "Hello World"; }
}

public class Children : Parent
{
    public Children() { World = "World"; }
}

但是,也许您正在寻找更像这样的东西:

public interface IParent
{
    String World { get; }
}

public class Parent : IParent
{
    public String World { get; private set; }
    public Parent(String thing) { World = "Hello " + thing; }
}

public class Children : Parent
{
    public Children() : base("World") { }
}