我正在尝试执行这样的代码:
IFoo = Interface
procedure DoFoo;
end;
TFoo = class (TInterfaceObject, IFoo)
.....
procedure DoFoo;
end;
TFoo2 = class (TInterfaceObject)
......
end;
TGenClass = class
class function DoSomething<T: class, cronstructor>: T;
end;
class function TGenClass.DoSomething<T>: T;
var Obj: T;
Foo: IFoo;
begin
Obj := T.Cretae;
if Obj.GetInterfaceEntry(IFoo) <> nil then
begin
Obj.GetInterface(IFoo, Foo);
Foo.DoFoo;
end;
result := Obj;
end;
......
var f: TFoo;
f2: TFoo2;
begin
f:= TGenClass.DoSomeThing<TFoo>;
f2:= TGenClass.DoSomeThing<TFoo2>;
f2.free;
f.free;
end;
当我执行此代码时, f.free 引发异常,因为我想它已经是免费的,因为如果我评论这行
Obj.GetInterface(IFoo, Foo);
Foo.DoFoo;
这行得通。
¿ 如何在没有自由对象的情况下执行 IFoo 接口?
谢谢。
添加:
谢谢大家。我明白。
我试图以相同的结果返回 IFoo。我的问题是 T 不能是 TInterfacedObject。我尝试转换的 Java 代码是:
public void dataIterate(int recNo, ResultSet data) throws SQLException {
try {
Constructor c = itemClass.getDeclaredConstructor();
c.setAccessible(true);
Object item = c.newInstance();
if (item instanceof CustomInitialize) ((CustomInitialize)item).initialize(data);
else {
if (metadata == null ) metadata = data.getMetaData();
for (int i=1; i<= metadata.getColumnCount(); i++)
assignProperty(itemClass, item, "set"+metadata.getColumnName(i).toLowerCase(), data.getObject(i));
}
add((E)item);
} catch (Exception ex) {
throw new SQLDataException(ex);
}
..........
德尔福示例代码:
program Project4;
{$APPTYPE CONSOLE}
{$R*.res}
uses
System.SysUtils, System.Rtti;
type
IFoo = Interface
['{F2D87AE6-1956-4B82-A28F-DC011C529849}']
procedure DoFoo;
end;
TFoo = class (TInterfacedObject, IFoo)
private
FName: String;
public
procedure DoFoo;
property Name: String Read FName write FName;
end;
TFoo2 = class (TObject)
private
FName: String;
published
property Name: String Read FName write FName;
end;
TGenClass = class
class function DoSomething<T: class, constructor>: T;
end;
class function TGenClass.DoSomething<T>: T;
var Obj: T;
Foo: IFoo;
Ap: TRttiProperty;
Ctx: TRttiContext;
begin
Obj := T.Create;
if Obj.GetInterfaceEntry(IFoo) <> nil then
begin
Obj.GetInterface(IFoo, Foo);
Foo.DoFoo;
end;
Ctx.GetType(TypeInfo(T)).GetProperty('Name').SetValue(TObject(Obj),'AName');
result := Obj;
end;
{ TFoo }
procedure TFoo.DoFoo;
begin
writeln('Foo executed.');
end;
var f: TFoo;
f2:TFoo2;
begin
try
f:= TGenClass.DoSomeThing<TFoo>;
f2:= TGenClass.DoSomeThing<TFoo2>;
writeln(f2.Name);
writeln(f.Name); //<-- raise exception
f.free;
f2.Free;
readln;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;