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

如何在Delphi中覆盖Class属性getter

发布时间:2020-12-15 09:17:11 所属栏目:大数据 来源:网络整理
导读:我定义了一个基类和一些派生类,它们永远不会被实例化.它们只包含类函数和两个类属性. 问题是Delphi要求使用static关键字en声明类属性的属性get方法,因此不能将其声明为virtual,因此我可以在派生类中覆盖它. 所以这段代码会导致编译错误: TQuantity = class(
我定义了一个基类和一些派生类,它们永远不会被实例化.它们只包含类函数和两个类属性.

问题是Delphi要求使用static关键字en声明类属性的属性get方法,因此不能将其声明为virtual,因此我可以在派生类中覆盖它.

所以这段代码会导致编译错误:

TQuantity = class(TObject)
    protected
      class function GetID: string; virtual; //Error: [DCC Error] E2355 Class property accessor must be a class field or class static method
      class function GetName: string; virtual;
    public
      class property ID: string read GetID;
      class property Name: string read GetName;
    end;

    TQuantitySpeed = class(TQuantity)
    protected
      class function GetID: string; override;
      class function GetName: string; override;
    end;

所以问题是:如何定义一个类属性,其结果值可以在派生类中重写?

使用Delphi XE2,Update4.

更新:
解决了David Heffernan使用函数代替属性的建议:

TQuantity = class(TObject)
    public
      class function ID: string; virtual;
      class function Name: string; virtual;
    end;

    TQuantitySpeed = class(TQuantity)
    protected
      class function ID: string; override;
      class function Name: string; override;
    end;

解决方法

How do you define a class property whose resulting value can be overridden in derived classes?

你不能,正如编译器错误消息所表明的那样:

E2355 Class property accessor must be a class field or class static method

类字段在通过继承关联的两个类之间共享.所以不能用于多态.而类静态方法也不能提供多态行为.

使用虚拟类函数而不是类属性.

(编辑:李大同)

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

    推荐文章
      热点阅读