简体   繁体   English

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

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

I have following piece of code: 我有以下代码:

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

The Wall and Floor class both inherit from Tile. Wall和Floor类都继承自Tile。 At another point in the program I have a if-statement which goes like this for example: 在程序的另一点,我有一个if语句,例如:

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

The tiles are a two-dimensional array of the Tile class and the content of them gets initialized either as a Floor or Wall. tile是Tile类的二维数组,其内容被初始化为Floor或Wall。 So if the tile is a Wall it is Digable (and should return true) but no matter what it always returns false, thus, not executing other code. 因此,如果图块是Wall,则它是Digable(并且应该返回true),但是无论它总是返回false,因此都不会执行其他代码。 Since I am not familiar with C# I suppose I am doing something wrong Syntax-wise, any suggestions? 因为我不熟悉C#,所以我想我在语法方面做错了什么,有什么建议吗?

The Equals method is for testing if two values are equivalent (in some way), for example, to test if two variables of type Floor refer to the same instance in memory. Equals方法用于测试两个值是否相等(以某种方式),例如,用于测试Floor类型的两个变量是否引用内存中的同一实例。

To test if an object is of a certain type, use the is operator : 要测试对象是否属于某种类型,请使用is运算符

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

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

Or as Rotem suggests, you can modify your classes to make isDigable and isGround virtual methods and override them in your child classes, like this: 或者如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