简体   繁体   English

使用(Object as TClass)和TClass(Object)之间的区别有什么区别

[英]What's the difference between casting using (Object as TClass) and TClass(Object)

Got an issue where MyObj.classnameis(TMyClass.classname) is true and TMyClass(MyObj) works but (MyObj as TMyclass).doSomething throws a conversion error. 有一个问题, MyObj.classnameis(TMyClass.classname)为真, TMyClass(MyObj)工作,但(MyObj as TMyclass).doSomething引发转换错误。

I don't really want any help with that junk, although if you want to put it in the comments that'd be super. 我真的不希望任何有关垃圾的帮助,不过如果你想把它放在那些超级的评论中。 I just would like to know what the difference between Obj as Class and Class(Obj) is. 我只是想知道Obj as ClassClass(Obj)之间的区别是什么。

An as-cast checks the actual object type to make sure the cast is valid, and raises an exception if it's not. as-cast检查实际的对象类型以确保转换有效,如果不是则引发异常。 A "hard cast" ( TMyClass(MyObj) style) does not check, it just tells the compiler to assume the cast is valid. “硬强制转换”( TMyClass(MyObj)样式)不检查,它只是告诉编译器假设TMyClass(MyObj)是有效的。

If you've got a situation where ClassNameIs returns true but the as-cast fails, that means you have two different classes in two different units with the same name, and the as-cast is trying to cast to the wrong one. 如果你遇到ClassNameIs返回true但是as-cast失败的情况,那意味着你有两个不同的类,它们在两个不同的单元中具有相同的名称,并且as-cast试图转换为错误的类。 This also means that your hard-cast is casting to the wrong one, which could potentially lead to memory corruption. 这也意味着您的强制转换是错误的,这可能会导致内存损坏。

Run a full project search for "TMyclass =" to see where your multiple declarations are, and either rename one of the classes or use a full definition (obj as MyUnit.TMyClass) so the compiler will know which class you're trying to cast to. 运行完整项目搜索“TMyclass =”以查看多个声明的位置,并重命名其中一个类或使用完整定义(obj作为MyUnit.TMyClass),以便编译器知道您要尝试转换哪个类至。

Addition to Mason's post: Instead of a searching through your code, you could also call a method like this one at the location that gives you problem. 除了Mason的帖子之外:您还可以在提供问题的位置调用类似这样的方法,而不是搜索您的代码。

function GetClassInheritance(Obj : TObject) : string;
var ClassRef : TClass;
begin
  Result := '';
  ClassRef := obj.ClassType;
  Result := ClassRef.ClassName;
  ClassRef := ClassRef.ClassParent;
  while assigned(ClassRef) do
  begin
    Result    := ClassRef.ClassName + '.' + Result;
    ClassRef  := ClassRef.ClassParent;
  end;

  Result := '(' + obj.ClassType.UnitName + ')' + Result
end;

That will return you a string formated as (UnitName)TObject.TPersistent.TComponent.... I don't remember seeing "ClassType.UnitName" in older version of delphi, so that part might not work with them, but the rest should. 这将返回一个格式化为(UnitName)TObject.TPersistent.TComponent的字符串....我不记得在旧版本的delphi中看到“ClassType.UnitName”,因此该部分可能无法使用它们,但其余的应该。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM