本文介绍了使用(Object as TClass)和TClass(Object)之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个问题,其中 MyObj.classnameis(TMyClass.classname)为true, TMyClass(MyObj) (MyObj as TMyclass).doSomething 引发转换错误。

Got an issue where MyObj.classnameis(TMyClass.classname) is true and TMyClass(MyObj) works but (MyObj as TMyclass).doSomething throws a conversion error.

我真的不想帮助那些垃圾,虽然如果你想把它放在评论中是超级的。我只想知道 Obj之间的区别 Class(Obj) 是。

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.

推荐答案

铸件检查实际对象类型,有效,如果不是,则引发异常。 hard cast( TMyClass(MyObj) style)不检查,它只是告诉编译器假设转换是有效的。

An as-cast checks the actual object type to make sure the cast is valid, and raises an exception if it's not. A "hard cast" (TMyClass(MyObj) style) does not check, it just tells the compiler to assume the cast is valid.

如果你有一个情况,ClassNameIs返回true但as-cast失败,这意味着你有两个不同的类在两个不同的单位具有相同的名称,并且as-cast试图转换错了一个。

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. This also means that your hard-cast is casting to the wrong one, which could potentially lead to memory corruption.

运行完整的项目搜索TMyclass =可以看到其中你的多个声明是,并重命名其中一个类或使用一个完整的定义(obj作为MyUnit.TMyClass),所以编译器将知道你试图投射到哪个类。

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.

这篇关于使用(Object as TClass)和TClass(Object)之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 22:45