如何访问对象内部的变量?

How to access variables inside an object?

我正在创建一种算法,根据动物的大小和类型在火车上装满动物。

想象动物 class 中的动物对象具有 typesize

/* 0 = Carnivore, Carnivores will eat other animals which are smaller or the same size.
 * 1 = Herbivore
 * Animal sizes 1, 3, 5 are currently available.
 * A trainwagon can fit a maximum of 10 points. The wagon needs to filled optimally.
 * A new wagon is added if there are still animals which need to board the train. 
 */

public Animal(int type, int size)
{
    this.type = type;
    this.size = size;
}

我需要动物的价值来对它们进行排序。因此,我创建了一个覆盖 ToString() 方法来获取值。

public override string ToString()
{
    string animalInformation = type.ToString() + size.ToString();
    return animalInformation.ToString();
}

我目前通过分离字符串的字符并将它们转换回整数来解决它。

int animalType = Convert.ToString(animalInformation[0]); 
int animalSize = Convert.ToString(animalInformation[1]);

我的问题是:是否有另一种技术可以访问动物对象中的变量,因为双重转换以不必要的方式影响了我的算法的性能。

除非问题中没有明显的细节,否则您应该只为字段创建属性,即

public readonly struct Animal
{
    public int Type { get; }
    public int Size { get; }

    public Animal(int type, int size)
    {
        Type = type;
        Size = size;
    }
}

可以使用 linq 进行排序。 'ThenBy(...)' 只有在需要按两个属性排序时才需要:

var sortedAnimals = animals.OrderBy(animal => animal.Type).ThenBy(animal => animal.Size);

如评论中所述,如果您只想允许某些类型和大小的值,您可能应该使用 enums。或者至少验证参数并在验证失败时抛出异常。

再看看你的构造函数:

public Animal(int type, int size)
{
    this.type = type;
    this.size = size;
}

这意味着 typesizeAnimal class 的数据成员,这意味着 Animal 的任何实例都有一个 typesizethis.type 不是变量,而是对象的数据成员,它与变量的可变性相似,但它是对象的固有属性。如果你做类似

Animal animal = new Animal(1, 1);

然后你无法到达animal.type,这意味着animal.type不是public,而是privateprotected。如果它是 public,您将能够到达它。但是,不要将其更改为 public,如果您保护您的字段免受我此时未描述的一些有问题的访问,那将是很好的。相反,您可以定义 getter,例如

public int getType() {
    return this.type;
}

public int getSize() {
    return this.size;
}

或一些只读的 properties 并通过这些获取值。