繁体   English   中英

C#this.Equals(typeof(...));

[英]C# this.Equals(typeof(…));

我有以下代码:

class Tile
{
    public TCODColor color { get; protected set; }
    public int glyph { get; protected set; }

    public Boolean isDigable()
    {
        return this.Equals(typeof(Wall));
    }
    public Boolean isGround()
    {
        return this.Equals(typeof(Floor));
    }
}

Wall和Floor类都继承自Tile。 在程序的另一点,我有一个if语句,例如:

public void dig(int x, int y)
{
    if (tiles[x, y].isDigable())
    {
        tiles[x,y] = new Floor();
    }
}

tile是Tile类的二维数组,其内容被初始化为Floor或Wall。 因此,如果图块是Wall,则它是Digable(并且应该返回true),但是无论它总是返回false,因此都不会执行其他代码。 因为我不熟悉C#,所以我想我在语法方面做错了什么,有什么建议吗?

Equals方法用于测试两个值是否相等(以某种方式),例如,用于测试Floor类型的两个变量是否引用内存中的同一实例。

要测试对象是否属于某种类型,请使用is运算符

public Boolean isDigable()
{
    return this is Wall;
}

public Boolean isGround()
{
    return this is Floor;
}

或者如Rotem建议的那样,您可以修改您的类以使其成为isDigableisGround 虚拟方法,并在子类中覆盖它们,如下所示:

class Tile
{
    public TCODColor color { get; protected set; }
    public int glyph { get; protected set; }

    public virtual bool isDigable() 
    { 
        return false; 
    }

    public virtual bool isGround() 
    { 
        return false; 
    }
}

class Wall: Tile
{
    public override bool isDigable()
    { 
        return true; 
    }
}

class Floor : Tile
{
    public override bool isGround()
    { 
        return true; 
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM