最快的类型比较?

Jam*_*zzi 6 c# xna types

以下事件可能每帧被调用数百次.

public bool OnCollision(Body body1, Body body2)
{
 if(body2.Tag is Dog)
      ((Dog)body2.Tag).Bark();
}
Run Code Online (Sandbox Code Playgroud)

我知道使用"is"会导致演员表演,然后当我想用它做某事时,再次使用它.有没有更有效的方法来检查类型?我做了一个控制台应用程序尝试"if(body2.Tag.GetType()== typeOf(Dog))"但它似乎比使用"是"更慢.

谢谢.

Jam*_*ran 19

 if(body2.Tag is Dog)
Run Code Online (Sandbox Code Playgroud)

实际编译为

Dog Temp = body2.Tag as Dog;
if (temp != null)
Run Code Online (Sandbox Code Playgroud)

在你的代码中,你再次进行演员表演.更好的是:

Dog dog = body2.Tag as Dog;
if (dog != null)
{
    dog.Bark();
}
Run Code Online (Sandbox Code Playgroud)


jos*_*rry 6

我只想在Body对象上创建一个名为Collided的抽象方法:

abstract class Body
{
   abstract void Collision(Body other);
}

class Dog : Body
{
   public override void Collision(Body other) {
      this.Bark();
   }

   public void Bark() { ... }
}
Run Code Online (Sandbox Code Playgroud)

然后在碰撞函数中,只需在相关实体上调用碰撞.

public bool OnCollision(Body body1, Body body2)
{
   body2.Collision(body2);
}
Run Code Online (Sandbox Code Playgroud)

这样任何类型的物体都可以在发生碰撞时做任何需要的事情,你甚至可以优化它以跟踪哪些物体已被告知彼此碰撞并减少你必须执行的函数调用的数量:

public bool OnCollision(Body body1, Body body2)
{
   // Record that these two objects have been notified of a collision
   // then when these same objects are the only two operands in subsequent calls
   // you can just short circuit the calls.
   if(!AlreadyNotifiedOfCollision(body1, body2))
   {
      body1.Collision(body2);
      body2.Collision(body1);
      NotifiedOfCollision(body1, body2);
   }
}
Run Code Online (Sandbox Code Playgroud)

当然,必须进行经验测试,以验证此检查比实际只进行两次调用更快...