我想出了以下易于擴展的“位桶”:
unit BitBucket;
interface
type TBitBucket = class
private
class procedure ThrowAway<T>(value: T); static;
public
class property Integer: Integer write ThrowAway;
class property String_: String write ThrowAway;
class property Extended: Extended write ThrowAway;
class property Boolean: Boolean write ThrowAway;
end;
implementation
class procedure TBitBucket.ThrowAway<T>(value: T);
begin
end;
end.
然而,雖然 IDE 中沒有波浪線,但它不會編譯,并出現以下錯誤:
[dcc32 Error] BitBucket.pas(9): E2008 Incompatible types
[dcc32 Error] BitBucket.pas(10): E2008 Incompatible types
[dcc32 Error] BitBucket.pas(11): E2008 Incompatible types
[dcc32 Error] BitBucket.pas( 12): E2008 不兼容的型別
有沒有我遺漏的技巧可以使這個編譯?我嘗試將泛型型別引數指定為ThrowAway,但這會導致更多錯誤。顯而易見的替代ThrowAway方法是為每種型別撰寫一個方法,但這會很快導致大量代碼無所作為。
對于那些想知道為什么在 delphi 中,您可以使用編譯器開關來防止使用函式而不分配它們的回傳值以與舊代碼兼容的人。使用 BitBucket,您可以說BitBucket.Integer := FunctionThatHasSideEffectsAndReturnsAnInteger(...);,而無需創建新變數。我也覺得這很有趣。
uj5u.com熱心網友回復:
您將泛型與變體混淆了。你需要這樣的東西:
unit BitBucket;
interface
type
TBitBucket<T> = class
private
class procedure ThrowAway(const Value: T); static;
class var FVar: T;
public
class property MyProperty: T read FVar write ThrowAway;
end;
implementation
class procedure TBitBucket<T>.ThrowAway(const Value: T);
begin
FVar := Value;
end;
end.
當您訪問它時,直到運行時才決定型別
TBitBucket<Integer>.MyProperty := 2;
uj5u.com熱心網友回復:
這是我能想到的最短的解決方案
type TBitBucket = class
class var ThrowAway: variant;
end;
用法
type test = class
procedure Test;
end;
implementation
{ test }
procedure test.Test;
begin
TBitBucket.ThrowAway := 'AString';
TBitBucket.ThrowAway := 1;
TBitBucket.ThrowAway := 1.1234;
TBitBucket.ThrowAway := true;
end;
T 值示例
這是一個使用 TValue 代替 system.RTTI 的示例,允許將物件放入存盤桶
type TBitBucket = class
class var ThrowAway: Tvalue;
end;
type test = class
procedure Test;
end;
implementation
{ test }
procedure test.Test;
begin
TBitBucket.ThrowAway := 'AString';
TBitBucket.ThrowAway := 1;
TBitBucket.ThrowAway := 1.1234;
TBitBucket.ThrowAway := true;
TBitBucket.ThrowAway := TObject.Create;
end;
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/381757.html
標籤:德尔福
上一篇:Delphi停靠表單隱藏面板
