Delphi属性需要一个常量参数吗?如果是这样,为什么?
发布时间:2020-12-15 04:10:14 所属栏目:大数据 来源:网络整理
导读:考虑以下(无法编译)代码: program AttributesTestProgram;{$APPTYPE CONSOLE}uses SysUtils,Classes,RTTI;type TDisplayTextAttribute = class(TCustomAttribute) private FDisplayText: string; public constructor Create(aDisplayText: string); propert
|
考虑以下(无法编译)代码:
program AttributesTestProgram;
{$APPTYPE CONSOLE}
uses
SysUtils,Classes,RTTI;
type
TDisplayTextAttribute = class(TCustomAttribute)
private
FDisplayText: string;
public
constructor Create(aDisplayText: string);
property DisplayText: string read FDisplayText write FDisplayText;
end;
constructor TDisplayTextAttribute.Create(aDisplayText: string);
begin
FDisplayText := aDisplayText;
end;
function GetFirstName: string;
begin
Result := 'First Name';
end;
type
TCustomer = Class(TObject)
private
FFirstName: string;
FLastName: string;
FStreetAddress: string;
FZIP: string;
FState: string;
FCity: string;
FPhone: string;
published
[TDisplayTextAttribute(GetFirstName)]
property FirstName: string read FFirstName write FFirstName;
end;
begin
// Code that does the work removed for clarity....
Readln;
end.
我很自然地想知道为什么这个错误无法编译: [DCC Error] AttributesTestProgram.dpr(40): E2026 Constant expression expected 我认为它与属性必须在编译器时间绑定的想法有关,或者沿着那些行绑定. 因此,我的问题是这样的: 有没有办法在这里“击败系统”并获得属性中的那个点的运行时值? 解决方法
是的,您需要常量,因为参数在编译时被计算为常量并存储在RTTI表中.此外,属性属于类,而不属于对象实例,因此如果您有多个TCustomer,您的想法将变得荒谬.
您可以通过为属性提供无参数构造函数(或根本没有构造函数)并将DisplayText属性更改为接受字符串或可从中提取字符串的对象的方法来击败系统. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
