加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

delphi – 在将“增强记录”分配给普通“数据类型”变量时,我会

发布时间:2020-12-15 09:24:40 所属栏目:大数据 来源:网络整理
导读:首先,我需要知道,如果我想做的事情是可能的.如果有可能,我需要知道如何. 它更容易证明问题??而不是解释它,所以这里: 我有一个“增强记录”(目的 – 虽然对这个问题不重要 – 是产生一个“智能字符串”类型,以取代普通的字符串类型): TLKString = record Va
首先,我需要知道,如果我想做的事情是可能的.如果有可能,我需要知道如何.

它更容易证明问题??而不是解释它,所以这里:

我有一个“增强记录”(目的 – 虽然对这个问题不重要 – 是产生一个“智能字符串”类型,以取代普通的字符串类型):

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的“实例”)赋值给普通的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;

这就是我解开的地方,因为(我相信你会注意到),上面的剪辑的最后一行产生了E2010不兼容的类型:’string’和’TLKString’.我当然知道会出现这种情况……我不知道是否可以通过在TLKString记录类型上重载操作符来克服,如果是这样,我需要重载哪个运算符来执行它.

如果这是不可能的,那么它会让我觉得CodeGear和Embarcadero有点愚蠢,它有Implicit和Explicit运算符来处理值到增强Record类型的赋值,但没有运算符来处理逆.

解决方法

好吧,我自己已经回答了……这就是我所说的“令人眼花缭乱的明显”.

这是解决方案(为了他人的利益)

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;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读