生成TStringList派生类的问题(在线等待)
Ta =Class(TStringList)
private
public
constructor Create(n:integer);
destructor Destroy;override;
end;
implementation
constructor Ta.Create(n:Integer);
begin
inherited create;
self.SetCapacity(n);
end;
destructor Ta.Destroy;
begin
end;
为什么总是报地址访问错误?
[解决办法]
给你看看我写的,和你的是一样的,在我这是不会报错的!共同学习吧!
{------------------------------------------
TMyStringList类定义单元
-------------------------------------------}
unit uMyStringList;
interface
uses Classes;
type
TMyStringList = class(TStringList)
public
constructor Create(n: Integer);
destructor Destroy(); override;
end;
implementation
{ TMyStringList }
constructor TMyStringList.Create(n: Integer);
begin
inherited Create;
Self.SetCapacity(n);
end;
destructor TMyStringList.Destroy;
begin
inherited;
end;
end.
{------------------------------------------
TMyStringList类使用
-------------------------------------------}
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, uMyStringList;
type
TForm1 = class(TForm)
Button1: TButton;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
sl: TMyStringList;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
var
i: Integer;
begin
for i := 0 to sl.Count - 1 do
begin
Self.Caption := Self.Caption + sl[i];
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
var
i: Integer;
begin
sl := TMyStringList.Create(10);
for i := 0 to 10 do
begin
sl.Add(IntToStr(i));
end;
end;
end.
[解决办法]
- Delphi(Pascal) code
type Ta =Class(TStringList) public constructor Create(n:integer); reintroduce; destructor Destroy; override; end;{$R *.DFM}procedure TForm1.FormCreate(Sender: TObject);begin with ta.Create(6) do try Add('This is a beautiful world!'); Caption := Text; finally Free; end;end;{ Ta }constructor Ta.Create(n: integer);begin inherited Create(); SetCapacity(n);end;destructor Ta.Destroy;begin inherited;end;
[解决办法]
with ta.Create(6) do
try
Add('This is a beautiful world!');
Caption := Text;
finally
Free;
end;
这样写没有问题的,with ta.Create(6) do 一句已经实例化 Ta 了,所有下面的Try finally end 块可以操作...
[解决办法]
7楼代码等效于9楼代码
这就是 with * do的作用
楼主的不想每次用都实例化,且应用中里需要一个这样的列表 可以用单实例模型
- Delphi(Pascal) code
Ta =Class(TStringList) private public constructor Create(n:integer); destructor Destroy;override; end; implementation constructor Ta.Create(n:Integer); begin inherited create; self.SetCapacity(n); end; destructor Ta.Destroy; begin end; // 注意以下代码function MyTa(n: Integer): Ta;var _VAR_LIST: Ta = nil;function MyTa(n: Integer): Ta;begin if Not Assigned(_VAR_LIST) then _VAR_LSIT = Ta.Create(n) else _VAR_LIST.SetCapacity(n); Result := _VAR_LIST; end;使用时直接用就行了MyTa(100);