“As”受限通用类型的运算符 [英] "As" operator for constrained generic types
本文介绍了“As”受限通用类型的运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑:
TTest <T : class, constructor> = class
public
function CreateMyObject : T;
end;
function TTest<T>.CreateMyObject : T;
var
Obj : TObject;
begin
Obj := T.Create;
Result := (Obj as T);
end;
为什么这不可能?编译器为 as 运算符产生不适用于此类型的运算符错误消息。 T被限制为一个类类型,所以这应该是正常的,不应该吗?
Why isn't this possible? Compiler yields an "Operator not applicable to this type" error message for the as operator. T is constrained to be a class type, so this should work, shouldn't it?
感谢您的帮助。
推荐答案
我遇到同样的问题,并通过在课堂中添加低级别的指针复制方法来解决这个问题:
I ran into the same problem and solved it by adding a low-level pointer-copy method to the class as a workaround:
TTest <T : class, constructor> = class
private
function _ToGeneric(AItem: TObject): T; inline; //inline, so it's a little faster
public
function CreateMyObject : T;
end;
function TTest<T>.CreateMyObject : T;
var
Obj : TObject;
begin
Obj := T.Create;
Result := _ToGeneric(Obj);
end;
function TTest<T>._ToGeneric(AItem: TObject): T;
begin
System.Move(AItem,Result,SizeOf(AItem))
end;
这篇关于“As”受限通用类型的运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文