加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 为什么这个从接口到类的失败?

发布时间:2020-12-15 03:58:14 所属栏目:百科 来源:网络整理
导读:private Vector2 ResolveCollision(ICollidable moving,ICollidable stationary){ if (moving.Bounds.Intersects(stationary.Bounds)) { if (moving is Player) { (Player)moving.Color = Color.Red; } } // ...} 我有一个实现ICollidable的类Player.为了调
private Vector2 ResolveCollision(ICollidable moving,ICollidable stationary)
{
    if (moving.Bounds.Intersects(stationary.Bounds))
    {
        if (moving is Player)
        {
            (Player)moving.Color = Color.Red;
        }
    }
    // ...
}

我有一个实现ICollidable的类Player.为了调试目的,我只是试图将一堆ICollidables传递给这个方法,并在播放器时做一些特殊的操作.但是,当我尝试向ICollidable的玩家做演员时,我发现错误告诉我,ICollidable没有Color属性.

我不能这样做,还是我做错了?

解决方法

我建议使用as而不是:
Player player = moving as Player;
if (player != null)
{
    player.Color = Color.Red;
}

优点是您只进行一次类型检查.

你的代码不工作的具体原因(如其他答案所述)是因为operator precedence.运算符是一个主运算符,其优先级高于作为一元运算符的运算符.您的代码解释如下:

(Player)(moving.Color) = Color.Red;

根据其他答案建议添加括号解决了这个问题,但改为使用而不是完全解决问题.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读