Delphi 关于错误E2002 File Type is not allowed here

技术交流,DH讲解.

最近写的程序里面想加入一个Log的功能,为了方便以后使用,所以就打算写一个控件.结果遇到了一个问题,这里和大家分享.


Procedure DoSetFile(ATxt: TextFile; Const Filename: String);
Begin
AssignFile(ATxt, Filename);
If FileExists(Filename) Then
Append(ATxt)
Else
Rewrite(ATxt);
End;
我是这样声明的,理论来说不应该有问题,结果Delphi就报了这个错误,文件类型不允许使用在这里.这个问题第一次遇到了,把函数声明改到控件里面也是这个错误.没有办法了 只有google一下.
看见一个老外也问了这个问题.
在一堆E文中 找呀找呀,终于看到一个人回答.给了我个提示.好吧我们改函数.
Procedure DoSetFile(Var ATxt: TextFile; Const Filename: String);
Begin
AssignFile(ATxt, Filename);
If FileExists(Filename) Then
Append(ATxt)
Else
Rewrite(ATxt);
End;
只是增加了一个var 结果就可以了.
因为我们这里可能改了ATxt,但是如果直接传值参肯定不行了,所以Delphi给了我们错误提示.
希望能对大家有帮助.

附上E文:有能力的朋友自己看下:

File types are not allowed as value parameters and as the base type of a file type itself. They are also not allowed as function return types, and you cannot assign them - those errors will however produce a different error message.

program Produce;

procedure WriteInteger(T: Text; I: Integer);
begin
  Writeln(T, I);
end;

begin
end.

In this example, the problem is that T is value parameter of type Text, which is a file type. Recall that whatever gets written to a value parameter has no effect on the caller's copy of the variable - declaring a file as a value parameter therefore makes little sense.

program Solve;

procedure WriteInteger(var T: Text; I: Integer);
begin
  Writeln(T, I);
end;

begin
end.

Declaring the parameter as a var parameter solves the problem.

Retrieved from "http://docwiki.embarcadero.com/RADStudio/en/E2002_File_type_not_allowed_here_(Delphi)"

好结束,我是DH.

原文地址:https://www.cnblogs.com/huangjacky/p/1620583.html