img*_*one 5 delphi integer properties read-write
在delphi类中声明属性时,是否可能有不同类型的结果?
例:
property month: string read monthGet(字符串) write monthSet(整数);
在这个例子中,我希望,在属性月份,当我:READ,我得到一个字符串; SET,我设置一个整数;
您可以获得的最接近的是使用运算符重载,但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.
Run Code Online (Sandbox Code Playgroud)
对于财产来说,没有办法做到这一点。属性具有单一类型。
实现目标的明显方法是拥有直接使用的 getter 和 setter 函数。
function GetMonth: string;
procedure SetMonth(Value: Integer);
Run Code Online (Sandbox Code Playgroud)
您可能决定将类型作为名称的一部分,以减少调用代码中的混乱。说GetMonthStr和SetMonthOrd。
您可以将这些函数公开为两个单独的属性。一个只读,另一个只写。
| 归档时间: |
|
| 查看次数: |
8761 次 |
| 最近记录: |