gpt4 book ai didi

c# - 当我们仍然可以在我们的抽象类中使用它们时,抽象属性的目的是什么?

转载 作者:太空宇宙 更新时间:2023-11-03 10:34:35 25 4
gpt4 key购买 nike

我们先看例子:

using System;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
Person p = new Manager();
Manager p2=new Manager();

p.Name = "Ahmad";
p.Introduce();
p.SayHello();
p2.SayHello();
p2 = (Manager)p;
p2.SayHello();
}
}

public abstract class Person
{
protected Person()
{
Name = "Reza";
Introduce();
}

public abstract string Name { get; set; }

public void SayHello()
{
Name = "Ali";
MessageBox.Show(Name);
}
public abstract void Introduce();
}

public class Manager : Person
{
public new void SayHello()
{
MessageBox.Show("Test2");
}

public override string Name { get; set; }

public override void Introduce()
{
MessageBox.Show("Hello " + Name);
}
}
}

起初我没有为基类编写构造函数。

据我所知,抽象方法的目的是强制派生类从中实现,因此我们不能在基类中实现抽象方法。

然后我添加了一个抽象属性。我看到我们可以在基类中初始化该属性并使用它。

1st: 抽象的目的不就是声明它们并让派生类来实现它吗?
为什么我们可以在基类中使用属​​性?

我们可以一开始只实现一个非抽象属性,这不会有什么不同。

然后我添加了构造函数,事情变得更加复杂。我们可以在构造函数中使用 Introduce() 方法从 Child 类调用 Introduce() (我从调试器中了解到)。

所以这里Child继承自Father,但是我们在Child中调用了一个方法from Father,这就很奇怪了,有点违反继承规则。

第二:我错过了什么?

编辑:

enter image description here

enter image description here

最佳答案

Wasn't the purpose of abstract to just declare them and let derived class to implement it? Why can we use the property in base class?

您不能使用基类中的抽象属性,因为您不能直接实例化它。您创建抽象属性的原因与创建抽象方法的原因相同,即确保您的派生类型实现它。

您的 Name 属性实际上并未使用 base-class 实例。当从 SayHello 调用时,它将转到 Name派生类型实现并使用它。

So Child inherits from Father here, but we call a method in Child from Father, which is strange and is somehow against the rules of inheritance. What have i missed?

不仅奇怪,它还是一个错误可能会导致运行时异常,因为子对象尚未初始化。如果您要访问 Introduce 中通过管理器构造函数(而不是通过字段初始化)实例化的任何 Manager 成员,您将得到一个异常:

public class Manager : Person
{
public Manager()
{
s = "Hello";
}

private string s;

public override string Name { get; set; }

public override void Introduce()
{
Console.WriteLine(s.ToLower());
}
}

当您现在调用 Introduce 时,您会看到一个 NullReferenceException,因为 s 尚未初始化。

如果您想在派生类型上调用抽象方法,请确保在 对象实例化之后执行此操作。或许通过基础上的 Initialize 方法。

您可以阅读 Virtual member call in a constructor了解更多信息:

if you make a virtual method call in a constructor, and it is not the most derived type in its inheritance hierarchy, that it will be called on a class whose constructor has not been run, and therefore may not be in a suitable state to have that method called.

关于c# - 当我们仍然可以在我们的抽象类中使用它们时,抽象属性的目的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28343978/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com