最快的一类比较? [英] Fastest Type Comparison?
本文介绍了最快的一类比较?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面的事件都不可能得到所谓轻车熟路的框架。
公共BOOL OnCollision(身体body1,身体body2)
{
如果(body2.Tag是狗)
((狗)body2.Tag).Bark();
}
据我了解,用是导致制作铸造,然后当我想用它做什么,它投第二次。有没有检查类型更有效的方法?我做了一个控制台应用程序试图如果(body2.Tag.GetType()== typeof运算(狗)),但它似乎是比使用是更慢。
感谢。
解决方案
如果(body2.Tag是狗)
实际上是编译成
狗温度= body2.Tag为犬;
如果(温度!= NULL)
在你的代码,你那么做再次施放。更好的是:
狗狗= body2.Tag为犬;
如果(狗!= NULL)
{
dog.Bark();
}
The following event can possibly get called hundreds of times a frame.
public bool OnCollision(Body body1, Body body2)
{
if(body2.Tag is Dog)
((Dog)body2.Tag).Bark();
}
I understand that using "is" causes a cast to be made and then when i want to do something with it, cast it a second time. Is there a more efficient way to check the type? I made a console app trying "if(body2.Tag.GetType() == typeOf(Dog))" but it appears to be even slower than using "is".
Thanks.
解决方案
if(body2.Tag is Dog)
is actually compiled as
Dog Temp = body2.Tag as Dog;
if (temp != null)
In your code, you're then doing the cast again. Better would be:
Dog dog = body2.Tag as Dog;
if (dog != null)
{
dog.Bark();
}
这篇关于最快的一类比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文