为什么这样的代码:

  w: word;
  s: String;
begin
  str(w, s);

在XE7中生成以下警告:
[dcc32 Warning] Unit1.pas(76): W1057 Implicit string cast from 'ShortString' to 'string'

汤姆

最佳答案

System.Str是一个固有功能,可以追溯到过去的时代。 documentation这样说:



由于这是内在的,因此可能会发生一些额外的情况。在幕后,通过调用产生ShortString的RTL支持函数来实现内部函数。然后,编译器魔术将其转换为string。并警告您隐式转换。编译器魔术转换

Str(w, s);

进入
s := _Str0Long(w);

其中_Str0Long是:
function _Str0Long(val: Longint): _ShortStr;
begin
  Result := _StrLong(val, 0);
end;

由于_Str0Long返回ShortString,因此编译器必须在分配给变量ShortString时生成代码以执行从strings的隐式转换。当然,您会很自然地看到W1057。

最重要的是,Str仅存在以保持与旧版Pascal ShortString代码的兼容性。新代码不应调用Str。您应该按照文档中的说明进行操作,然后调用IntToStr:
s := IntToStr(w);

也许:
s := w.ToString;

10-02 10:32