首页 > 解决方案 > 如何访问对象内部的变量?

问题描述

我正在创建一个算法来根据动物的大小和类型用动物填满火车。

type想象一个具有和的动物类中的动物对象size

/* 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]);

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

标签: c#algorithmsortingtostring

解决方案


再看看你的构造函数:

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

这意味着typesize是您的数据成员Animal class,这意味着任何实例Animal都有一个type或一个sizethis.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;
}

或一些只读属性并通过这些获取值。


推荐阅读