在一个复杂的应用程序中,我发现了一个关于类设计的小错误:
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type AboutMe= class
Name : String
end;
type AboutMe_more = class(AboutMe)
gender : String;
Birth : TDate;
end;
type Aboutme_complete = class (AboutMe_more)
adresss : String;
salery : Real;
name : String; /// name is already available a parent class
end;
type
TForm1 = class(TForm)
Button1: TButton;
procedure FormCreate(Sender: TObject);
private
{ Private-Deklarationen }
public
{ Public-Deklarationen }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
var _Aboutme_complete : Aboutme_complete ;
begin
_Aboutme_complete := Aboutme_complete.Create;
_Aboutme_complete.name := 'a coding error -> need refactoring ';
end;
end.
在“AboutMe_more”类中,错误地添加了字段名称。 我想知道如果我删除那个过时的名字字段会发生什么样的错误? 这个问题背后的麻烦(约100 K代码行,没有系统测试)
答案 0 :(得分:4)
name
类型中有两个名为Aboutme_complete
的变量。在AboutMe
中引入了一个,然后在Aboutme_complete
中引入了第二个隐藏第一个的AboutMe
。
name
的方法,成员Aboutme_complete
引用第一个变量。name
的方法,成员name
引用第二个变量。从Aboutme_complete
删除变量Aboutme_complete
可能会改变行为。那是因为现在只有一个变量,所有类的方法都将引用同一个变量。因此,正如代码所示,Aboutme_complete.name
中的方法引用AboutMe.name
,但如果您进行了更改,则代码将引用{{1}}。
这是否会破坏您的代码取决于代码是什么。只有你能知道答案,因为只有你有这个代码。