dcc32警告UnloadProcs.pas(59):W1035函数'GetType'的返回值可能未定义

use*_*132 1 delphi warnings function build delphi-xe2

有一种数据类型

type
TDataTypeId = (DataTypeId_String, DataTypeId_SmallInt, DataTypeId_Integer, DataTypeId_Word,
               DataTypeId_Boolean, DataTypeId_Float, DataTypeId_Currency,
               DataTypeId_BCD, DataTypeId_FmtBCD, DataTypeId_Date,
               DataTypeId_Time, DataTypeId_DateTime, DataTypeId_TimeStamp,
               DataTypeId_Bytes, DataTypeId_VarBytes, DataTypeId_Blob,
               DataTypeId_Memo, DataTypeId_Graphic, DataTypeId_fmtMemo,
               DataTypeId_FixedChar, DataTypeId_WideChar, DataTypeId_LargeInt,
               DataTypeId_Array, DataTypeId_FixedWideChar, DataTypeId_WideMemo);
Run Code Online (Sandbox Code Playgroud)

有一个函数接受包含这种类型的值之一的行,返回该值

Function GetType(str: string): TDataTypeId;
var
typeidx: TDataTypeId;
typestr: string;
begin
for typeidx := Low(TDataTypeID) to High(TDataTypeID) do
 begin
  typestr:=GetEnumName(TypeInfo(TDataTypeId),Ord(typeidx));
  typestr:=Copy(typestr, 12, length(typestr)-11);
  //Memo.Lines.Add(typestr+'\n');
  if (AnsiCompareStr(str, typestr)=0) then
     Result:=typeidx
 end;
 end;
Run Code Online (Sandbox Code Playgroud)

结果,有一个组件

[dcc32 Warning] UnloadProcs.pas(59): W1035 Return value of function 'GetType' might be undefined
Run Code Online (Sandbox Code Playgroud)

如何转换未出现警告的功能?

Dav*_*nan 5

编译器警告是准确的.如果if语句从未求值True,因为未找到匹配项,则循环不会分配给Result.然后函数退出而不指定值.

你的选择:

  1. Result在循环完成后,为值分配一个值,表示未找到匹配项.
  2. 循环完成后引发异常.

我还建议你exit在分配后立即Result.当你找到答案时,没有必要继续循环.

我可能会写这样的函数:

Function GetType(str: string): TDataTypeId;
var
  typestr: string;
begin
  for Result := low(Result) to high(Result) do
  begin
    typestr := GetEnumName(TypeInfo(TDataTypeId),Ord(typeidx));
    typestr := Copy(typestr, 12, length(typestr)-11);
    if AnsiSameStr(str, typestr) then
      exit;
  end;
  raise EEnumNotFound.CreateFmt('Enum not found: %s', [str]);
end; 
Run Code Online (Sandbox Code Playgroud)

注意使用Result变量作为循环变量.这是惯用的,可以减少您声明的局部变量的数量.

我同意您可以更有效地解决您的问题GetEnumValue,但我想向您展示如何以惯用的方式处理编译器警告.