Fastest Type Comparison?

前端 未结 4 1969
礼貌的吻别
礼貌的吻别 2021-01-12 11:49

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)bo         


        
4条回答
  •  孤城傲影
    2021-01-12 12:43

     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();
    }
    

提交回复
热议问题