gpt4 book ai didi

Delphi 属性读/写

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

在delphi类中声明属性时是否可能有不同类型的结果?

示例:

属性月份:字符串读取monthGet(字符串)写入monthSet(整数);

在示例中,我希望在属性(property)月份中,当我:读,我得到一个字符串; SET,我设置一个整数;

最佳答案

最接近的是使用 Operator Overloading但Getter/Setter必须是同一类型。没有办法改变这一点。

program so_26672343;

{$APPTYPE CONSOLE}
{$R *.res}

uses
System.SysUtils;

type
TMonth = record
private
FValue: Integer;
procedure SetValue( const Value: Integer );
public
class operator implicit( a: TMonth ): string;
class operator implicit( a: Integer ): TMonth;
property Value: Integer read FValue write SetValue;
end;

TFoo = class
private
FMonth: TMonth;
public
property Month: TMonth read FMonth write FMonth;
end;

{ TMonth }

class operator TMonth.implicit( a: TMonth ): string;
begin
Result := 'Month ' + IntToStr( a.Value );
end;

class operator TMonth.implicit( a: Integer ): TMonth;
begin
Result.FValue := a;
end;

procedure TMonth.SetValue( const Value: Integer );
begin
FValue := Value;
end;

procedure Main;
var
LFoo: TFoo;
LMonthInt: Integer;
LMonthStr: string;
begin
LFoo := TFoo.Create;
try
LMonthInt := 4;
LFoo.Month := LMonthInt;
LMonthStr := LFoo.Month;
finally
LFoo.Free;
end;
end;

begin
try
Main;
except
on E: Exception do
Writeln( E.ClassName, ': ', E.Message );
end;

end.

关于Delphi 属性读/写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26672343/

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