加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-15 09:25:46 所属栏目:大数据 来源:网络整理
导读:在我的工作场所,我们有一些代码,其中类函数引用Self,如果对象未初始化,则有效地创建潜在的访问冲突. Self的含义是否在类方法中更改为引用类而不是对象? 我认为这是唯一的原因是因为Self引用了另一个类函数而不是常规方法. 我创建了以下测试类: constructor
在我的工作场所,我们有一些代码,其中类函数引用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的使用减少了范围,因此降低了无意中引用局部变量而不是类成员的危险.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读