gpt4 book ai didi

delphi - 为什么当类方法使用 self 时,Delphi 编译器不发出警告?

转载 作者:行者123 更新时间:2023-12-03 15:25:23 25 4
gpt4 key购买 nike

在我的工作场所,我们有一些代码,其中类函数引用Self,如果对象未初始化,则实际上会造成潜在的访问冲突。类方法中 Self 的含义是否会更改为引用类而不是对象?

我认为它起作用的唯一原因是因为Self引用了另一个类函数而不是常规方法。

我创建了以下测试类:

constructor TTest.Create;
begin
FTest := 'Hej';
end;

procedure TTest.GoTest;
begin
ShowMessage(FTest);
end;

class procedure TTest.Test;
begin
Self.GoTest;
end;

但是,编译会引发错误:

[dcc32 Error] Unit1.pas(51): E2076 This form of method call only allowed for class methods or constructor

我还直接引用 FTest 进行测试,这给出了另一个错误:

[dcc32 Error] Unit1.pas(51): E2124 Instance member 'FTest' inaccessible here

但是我想知道,是否有可能出现 Self 在类方法中存在潜在危险的情况。

我知道,引用全局对象并假设它们存在总是不好的。

最佳答案

Does the meaning of Self change in a class method as to refer the class rather than the object?

在类方法中,Self 指的是该类。 documentation说:

In the defining declaration of a class method, the identifier Self represents the class where the method is called (which can be a descendant of the class in which it is defined.) If the method is called in the class C, then Self is of the type class of C. Thus you cannot use Self to access instance fields, instance properties, and normal (object) methods. You can use Self to call constructors and other class methods, or to access class properties and class fields.

A class method can be called through a class reference or an object reference. When it is called through an object reference, the class of the object becomes the value of Self.

编译器不会反对您使用Self,因为这是合法且受支持的操作。当您尝试使用实例成员、实例方法等时,它只会提示。

Self 在类方法中具有此含义,其原因与它在实例方法中存在的原因完全相同。它允许您完全指定符号,从而避免范围模糊。更重要的是,它允许您访问调用该方法的实际类。这可能是定义该方法的类的后代。

I wonder, however, whether it is possible to have a case where Self is potentially dangerous in class methods.

我没有看到这部分语言固有的任何特殊危险。事实上,Self 的使用缩小了范围,从而降低了无意中引用局部变量而不是类成员的危险。

关于delphi - 为什么当类方法使用 self 时,Delphi 编译器不发出警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16054887/

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