【问题标题】:C# this.Equals(typeof(...));C# this.Equals(typeof(...));
【发布时间】:2014-09-01 01:46:33
【问题描述】:

我有以下代码:

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。因此,如果图块是墙,则它是可挖掘的(并且应该返回 true),但无论如何它总是返回 false,因此,不会执行其他代码。由于我不熟悉 C#,我想我在语法方面做错了,有什么建议吗?

【问题讨论】:

    标签: c# this typeof equals-operator


    【解决方案1】:

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

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

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

    或者正如 Rotem 建议的那样,您可以修改您的类以在您的子类中创建 isDigableisGround virtual 方法和 override 它们,如下所示:

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

    【讨论】:

    • 理智的方法是使isDigableisGround 成为虚拟并让WallFloor 覆盖它们。正如它所写的那样,Tile 必须知道它的所有子类。
    • 完美,工作,谢谢! @Rotem 我知道,但我有理由这样做。
    • @Rotem 好建议。为了完整性,我已经包含了这样一个解决方案。
    • 如果您要走虚拟路线,不妨也将它们设为属性。
    • @JustinNiessner 是的,我开始将它们编写为属性,但后来我决定不想更改 太多 OP 的代码。我只是想强调多态性。
    猜你喜欢
    • 1970-01-01
    • 2011-02-08
    • 1970-01-01
    • 2010-12-31
    • 2011-07-20
    • 1970-01-01
    • 2011-01-29
    • 1970-01-01
    • 2012-01-11
    相关资源
    最近更新 更多