XE7中的Str会产生奇怪的警告

Tom*_*Tom 8 delphi string delphi-xe7

为什么这段代码:

  w: word;
  s: String;
begin
  str(w, s);
Run Code Online (Sandbox Code Playgroud)

在XE7中生成此警告:

[dcc32 Warning] Unit1.pas(76): W1057 Implicit string cast from 'ShortString' to 'string'
Run Code Online (Sandbox Code Playgroud)

汤姆

Dav*_*nan 5

System.Str是一个内在的功能,可以追溯到一个再见的时代.该文件说,这:

procedure Str(const X [:Width [:Decimals]]; var S:String);

....

注意:但是,在使用此过程时,编译器可能会发出警告:W1057从'%s'到'%s'(Delphi)的隐式字符串强制转换.

如果不需要具有预定义最小长度的字符串,请尝试使用IntToStr函数.

由于这是一个内在的,可能会有额外的事情发生.在幕后,内部函数通过调用RTL支持函数来实现,该函数产生一个ShortString.编译器魔术然后把它变成一个string.并警告你隐含的转换.编译器魔术转换

Str(w, s);
Run Code Online (Sandbox Code Playgroud)

s := _Str0Long(w);
Run Code Online (Sandbox Code Playgroud)

在哪里_Str0Long:

function _Str0Long(val: Longint): _ShortStr;
begin
  Result := _StrLong(val, 0);
end;
Run Code Online (Sandbox Code Playgroud)

由于_Str0Long回报ShortString,则编译器生成的代码从执行隐converstion ShortStringstring时,它分配给您的变量s.当然,你看W1057是很自然的.

底线是Str仅存在以保持与传统Pascal ShortString代码的兼容性.新代码不应该调用Str.您应该执行文档所说的内容并致电IntToStr:

s := IntToStr(w);
Run Code Online (Sandbox Code Playgroud)

也许:

s := w.ToString;
Run Code Online (Sandbox Code Playgroud)