LaK*_*ven 4 delphi overloading record operator-keyword delphi-xe2
首先,我需要知道,如果我想做的事情是可能的.如果有可能,我需要知道如何.
它更容易证明问题而不是解释它,所以这里:
我有一个"增强记录"(目的 - 虽然对这个问题不重要 - 是产生一个"智能字符串"类型,以取代普通的字符串类型):
TLKString = record
Value: String;
// Some methods here to operate on and build String values
// Allows me to assign String values directly to "instances"
// of this record type! I have others (hence "overload") to
// handle other data types (such as Integer etc.)
class operator Implicit(const AValue: String): TLKString; overload;
end;
Run Code Online (Sandbox Code Playgroud)
我现在可以使用这个TLKString类型,如下所示:
var
LSmartString: TLKString;
begin
LSmartString := 'Hello World'; // The "Implicit" operator then
// assigns this to LSmartString.Value
end;
Run Code Online (Sandbox Code Playgroud)
好的,到目前为止一切都很棒!现在我们解决了这个问题......
我需要能够将LSmartString的值(TLKString的"实例")赋值给普通的String变量...
var
LSmartString: TLKString;
LNormalString: String;
begin
LSmartString := 'Hello World';
// The next line works fine, but is not what I want!
LNormalString := LSmartString.Value;
LNormalString := LSmartString; // E2010 (Incompatible Types)
end;
Run Code Online (Sandbox Code Playgroud)
这就是我解开的地方,因为(我相信你会注意到),上面的剪辑的最后一行产生了E2010不兼容的类型:'string'和'TLKString'.我当然知道会出现这种情况......我不知道是否可以通过在TLKString记录类型上重载操作符来克服,如果是这样,我需要重载哪个运算符来执行它.
如果这是不可能的,那么它令我有点傻的CodeGear和Embarcadero公司的拥有Implicit和Explicit运营商来处理,以增强记录类型值的分配,但没有运营商处理的倒数.
好吧,我自己已经回答了......这就是我所说的"令人眼花缭乱的明显".
这是解决方案(为了他人的利益)
TLKString = record
Value: String;
// Some methods here to operate on and build String values
class operator Implicit(const AValue: String): TLKString; overload; // handles String to TLKString assignment
class operator Implicit(const AValue: TLKString): String; overload; // handles TLKString to String assignment! THIS IS THE ANSWER!
end;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
268 次 |
| 最近记录: |