首先,我需要知道我想做的事情是否可行。如果可能的话,我需要知道如何做。
演示问题比解释问题要容易得多,所以这里是:
我有一个“增强记录”(目的 - 虽然对这个问题并不重要 - 是生成一个“智能字符串”类型,以替换普通的字符串类型):
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;
我现在可以使用这个 TLKString 类型,如下所示:
var
LSmartString: TLKString;
begin
LSmartString := 'Hello World'; // The "Implicit" operator then
// assigns this to LSmartString.Value
end;
好的,到目前为止一切都很好!现在我们遇到问题了......
我需要能够将 LSmartString (TLKString 的“实例”)的值分配给普通的字符串变量......
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;
这就是我遇到困难的地方,因为(我相信你会注意到),上面片段的最后一行结果是E2010 不兼容的类型:“string”和“TLKString”。当然,我知道情况会是这样……我不知道是否可以通过在 TLKString 记录类型上重载运算符来克服这个问题,如果可以,我需要重载哪个运算符来完成它。
如果这不可能,那么 CodeGear 和 Embarcadero 让我觉得有点愚蠢Implicit
and Explicit
运算符来处理将值分配给增强的 Record 类型,但没有运算符来处理相反的情况。