将 TStream 转换为字符串?
Convert TStream to String?
在 Delphi 10.4 中,我尝试使用以下代码将 TStream
转换为 string
:
function MyStreamToString(aStream: TStream): string;
var
SS: TStringStream;
begin
if aStream <> nil then
begin
SS := TStringStream.Create('');
try
SS.CopyFrom(aStream, 0); // Exception: TStream.Seek not implemented
Result := SS.DataString;
finally
SS.Free;
end;
end else
begin
Result := '';
end;
end;
但是在这个代码行中,我得到一个异常“TStream.Seek not implemented”:SS.CopyFrom(aStream, 0);
为什么?我怎样才能“修复”这段代码?
该错误意味着您传递给函数的 TStream
对象根本没有实现 Seek()
。例如,如果您传递的是实际的 TStream
对象而不是派生对象,例如 TFileStream
、TMemoryStream
等,例如:
var
Strm: TStream;
begin
Strm := TStream.Create; // <-- ERROR
try
MyStreamToString(Strm);
finally
Strm.Free;
end;
end;
TStream
是一个抽象基础 class,它应该永远不会 被直接实例化。
在这种情况下,基 TStream
class 中的 32 位 Seek()
方法调用 64 位 Seek()
方法,但会引发“Seek如果未覆盖 64 位 Seek()
,则为“未实现”异常。 TStream
派生的 class 必须 override
32 位 Seek()
或 64 位 Seek()
,并且被覆盖的方法不得调用其覆盖的基TStream
方法。
因此,请确保将 有效 流对象传递给您的函数。
在 Delphi 10.4 中,我尝试使用以下代码将 TStream
转换为 string
:
function MyStreamToString(aStream: TStream): string;
var
SS: TStringStream;
begin
if aStream <> nil then
begin
SS := TStringStream.Create('');
try
SS.CopyFrom(aStream, 0); // Exception: TStream.Seek not implemented
Result := SS.DataString;
finally
SS.Free;
end;
end else
begin
Result := '';
end;
end;
但是在这个代码行中,我得到一个异常“TStream.Seek not implemented”:SS.CopyFrom(aStream, 0);
为什么?我怎样才能“修复”这段代码?
该错误意味着您传递给函数的 TStream
对象根本没有实现 Seek()
。例如,如果您传递的是实际的 TStream
对象而不是派生对象,例如 TFileStream
、TMemoryStream
等,例如:
var
Strm: TStream;
begin
Strm := TStream.Create; // <-- ERROR
try
MyStreamToString(Strm);
finally
Strm.Free;
end;
end;
TStream
是一个抽象基础 class,它应该永远不会 被直接实例化。
在这种情况下,基 TStream
class 中的 32 位 Seek()
方法调用 64 位 Seek()
方法,但会引发“Seek如果未覆盖 64 位 Seek()
,则为“未实现”异常。 TStream
派生的 class 必须 override
32 位 Seek()
或 64 位 Seek()
,并且被覆盖的方法不得调用其覆盖的基TStream
方法。
因此,请确保将 有效 流对象传递给您的函数。