内容简介:翻译自:https://stackoverflow.com/questions/28311978/how-to-cast-generic-t-to-a-tobject
我有一个方法需要返回一个对象.当然,只有T是一个对象才有意义:
function TGrobber<T>.Swipe: TObject;
var
current: T;
begin
{
If generic T is not an object, then there's nothing we can return
But we'll do the caller a favor and not crash horribly.
}
if PTypeInfo(TypeInfo(T))^.Kind <> tkClass then
begin
Result := nil;
Exit;
end;
//We *are* an object, return the object that we are.
current := Self.SwipeT;
Result := TObject(current); <--E2089 invalid class typecast
end;
如果T不是一个对象(例如Integer,String或OleVariant),那么它将返回nil,并且不会崩溃.
如果我们是一个对象(例如TCustomer,TPatron,TSalesOrder,TShape),那么我们可以很好地返回对象.
我不想混淆这个问题;但如果你看看IEnumerable,你会看到实际发生的事情.
奖金阅读
> Delphi: determine actual type of a generic?
> Conditional behaviour based on concrete type for generic class
回答
我会让TLama复制/粘贴答案以获得他的信誉:
function TGrobber<T>.Swipe: TObject;
var
current: T;
v: TValue;
begin
current := Self.SwipeT;
v := TValue.From<T>(current);
{
If generic T is not an object, then there's nothing we can return
But we'll do the caller a favor and not crash horribly.
}
if not v.IsObject then
begin
Result := nil;
Exit;
end;
Result := v.AsObject;
end;
我看到两个主要选择.如果泛型类型必须是类类型,并且在编译时知道,则应对类型应用约束:
type
TGrobber<T: class> = class
....
end;
或者,如果类型必须从特定类派生,则可以如下指定该约束:
type
TGrobber<T: TMyObject> = class
....
end;
一旦应用了约束,就可以直接进行分配.
Result := current;
这成为可能,因为编译器对您的泛型类型强制执行约束.因此知道赋值对所有可能的实例都有效.
我会评论一个泛型类有一个返回TObject的函数似乎很奇怪.为什么你的函数没有返回T?
如果你不能约束那么一个简单的指针类型转换是最干净的方法:
Result := PObject(@current)^;
显然你需要检查T是一个类类型,你已经证明了它的代码.
对于它的价值,自Delphi XE7以来,使用System.GetTypeKind检查类型的类型更简单:
if GetTypeKind(T) = tkClass then Result := PObject(@current)^ else Result := nil;
翻译自:https://stackoverflow.com/questions/28311978/how-to-cast-generic-t-to-a-tobject
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:- 运用 Java 8 写一个 通用 Map 转换工具类
- JavaScript进阶系列-类型转换、隐式类型转换
- Android 多国语言转换 Excel 和 Excel 转换为 string
- [SSL证书转换(一)]关于JKS 转换成 CRT 和 KEY
- c++中几种常见的类型转换。int与string的转换,float与string的转换以及string和long类型之间的相互...
- Protocol Buffer使用转换工具将proto文件转换成Java文件流程及使用
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。