【问题标题】:Why does Str() give "W1057 Implicit string cast from 'ShortString' to 'string'"?为什么 Str() 给出“W1057 Implicit string cast from 'ShortString' to 'string'”?
【发布时间】:2012-09-19 10:38:14
【问题描述】:

考虑:

function x_StrZero(N: Double; W: Integer; D: Integer = 0): String;
var S : String;
begin
  Str(N:W:D,S);   
  S := Trim(S);

这将 W1057 隐式字符串从“ShortString”转换为“字符串”

online doc 说:

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

还有

注意:但是,在使用此过程时,编译器可能会发出警告:W1057 Implicit string cast from '%s' to '%s' (Delphi)。

为什么会这样?

我想阻止这种丑陋的解决方法:

function x_StrZero(N: Double; W: Integer; D: Integer = 0): String;
var
  S : String;
  SS : ShortString;
begin
  Str(N:W:D,SS);
  S := Trim(String(SS));

我已阅读 Why does Delphi warn when assigning ShortString to string? 但这并没有回答这个问题。

【问题讨论】:

  • 如果这种解决方法对你来说很难看,你可以使用 format
  • 只是一个疯狂的猜测,你试过 S:Ansistring 和 {$O-} 吗? Str 是 TurboPascal 的古老函数,可能是 TP 字符串上的 asm 实现。虽然 IntToStr 缺少该功能,但我还是会避免使用那些古老的程序。
  • TJclNumericFormat 和函数 IntToStrZeroPad(Value, Count: Integer): string;也可能是可行的替代品
  • 正确的做法是停止使用Str
  • 我同意你的观点,它古代码

标签: delphi unicode delphi-xe2


【解决方案1】:
Str(N:W:D,S);   

编译为

S := System._Str2Ext(N, W, D);

其中System._Str2Ext 是一个返回类型为ShortString 的函数。它在分配给S 时转换为string。该警告虽然不易阅读,但它是正确的,但此时存在隐式转换。因此,要么通过避免Str 重新编写代码以使其没有隐式转换,要么关闭警告,或忽略警告。

【讨论】:

  • 谢谢,我在系统中没有找到
【解决方案2】:

您可以关闭该特定警告。这只是一个提醒,大多数情况下您的程序运行良好。我猜编译器仍然将String 视为ShortString 在内置的函数中,例如Str()Writeln()

【讨论】:

  • 您的意思可能是 Shortstring 而不是 AnsiStirng ?并且 WriteLn 可以很好地与 string==UnicodeString
  • 是的,我的错。我的意思是由编译器直接替换的例程
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-07
  • 2012-01-16
  • 1970-01-01
  • 2018-02-25
相关资源
最近更新 更多