是否可以傳送一個類名為參數,然後用其生成一個對象(50分)

  • 主题发起人 主题发起人 zwhc
  • 开始时间 开始时间
Z

zwhc

Unregistered / Unconfirmed
GUEST, unregistred user!
是否可以傳送一個類名為參數,然後用其生成一個對象。如:
Object createObj(Class cls) {
Object o;
//o = new cls();
return o;
}
 
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;
implementation
uses Unit2, Unit3;
{$R *.dfm}
function f(mName: string): Boolean;
var
FormClass: TFormClass;
begin
Result := True;
try
FormClass := TFormClass(FindClass(mName));
with TFormClass(FormClass).Create(Application)do
try
ShowModal;
finally
Free;
end;
except
Result := False;
end;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
RegisterClasses([TForm1, TForm2, TForm3]);
//要注册from类
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
f('TForm2');
f('TForm3');
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
UnRegisterClasses([TForm1, TForm2, TForm3]);
//要注消from类
end;

end.
 
就是类类型的概念了
你看看TApplication.CreateForm的源程序,会有所感受的。
 
多謝三位。可我是在 java 版提的問題 [:(]
 
这属于RTTI的范畴,比如以下实例代码
Object sss ;
try {
sss = Class.forName("java.awt.Button").newInstance() ;
System.out.println(sss.toString()) ;
} catch (Exception e) {
e.printStackTrace();
}
 

Similar threads

I
回复
0
查看
794
import
I
S
回复
0
查看
3K
SUNSTONE的Delphi笔记
S
S
回复
0
查看
2K
SUNSTONE的Delphi笔记
S
后退
顶部