在delphi类中声明属性时是否可能有不同类型的结果?
示例:
property month: string read monthGet(
的字符串 ) write monthSet(
的整数 );
在示例中,我希望,在属性月份时,我想: 读,我得到一个字符串; SET,我设置了一个整数;
答案 0 :(得分:7)
最接近的是使用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.
答案 1 :(得分:2)
这是不可能的。但属性不必直接与内部存储相对应,因此您可以这样做:
private
FMonth: Integer;
function GetMonthName: string;
...
property Month: Integer read FMonth write FMonth;
property MonthName: string read GetMonthName;
...
procedure TMyClass.GetMonthName: string;
begin
// code that finds name that corresponds to value of FMonth and returns it in Result.
end;
换句话说,您必须使用两个属性,一个是只写(或正常),一个是只读。
答案 2 :(得分:1)
对于房产没有办法做到这一点。酒店有单一类型。
实现目标的显而易见的方法是使用直接使用的getter和setter函数。
function GetMonth: string;
procedure SetMonth(Value: Integer);
您可能决定将名称的类型部分用于减少调用代码中的混淆。说GetMonthStr
和SetMonthOrd
。
您可以将这些功能公开为两个单独的属性。一个只读,另一个只写。
答案 3 :(得分:1)
你不能在Delphi中直接这样做。
你可以做的是拥有一个"铸造属性"像:
private
//...
intMonth: integer
//...
public
//...
property StrMonth: string read GetStrMonth write SetStrMonth;
property IntMonth: integer read intMonth write intMonth;
//...
end;
function YourClass.GetStrMonth: string;
begin
case intMonth of
1: Result := "January";
//...
end;
end;
procedure YourClass.SetStrMonth(Value: string);
begin
if StrMonth = "January" then
intMonth := 1;
//...
end;
end;