c# - 如何访问对象内部的变量?
问题描述
我正在创建一个算法来根据动物的大小和类型用动物填满火车。
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]);
我的问题是:是否有另一种技术可以访问动物对象中的变量,因为双重转换会以不必要的方式影响我的算法的性能。
解决方案
再看看你的构造函数:
public Animal(int type, int size)
{
this.type = type;
this.size = size;
}
这意味着type
和size
是您的数据成员Animal
class
,这意味着任何实例Animal
都有一个type
或一个size
。this.type
不是变量,而是对象的数据成员,由于其可变性,它类似于变量,但它是对象的固有属性。如果你做类似的事情
Animal animal = new Animal(1, 1);
然后你无法到达animal.type
,这意味着animal.type
不是public
,而是private
或protected
。如果它是,你将能够到达它public
。但是,不要将其更改为public
,如果您保护您的字段免受一些我现在没有描述的有问题的访问,那就太好了。相反,您可以定义 getter,例如
public int getType() {
return this.type;
}
public int getSize() {
return this.size;
}
或一些只读属性并通过这些获取值。
推荐阅读
- c# - IP 摄像机视频流纹理未提供给 Unity
- mongodb - Kubernetes MongoDb pod 内存使用差异
- oop - 将 Dart 枚举放入类或包导出文件中
- javascript - 简单的 HXR 请求返回 mysql 响应
- angular - 如何使用来自另一个组件的 onclick 事件更改 iframe src(角度)
- linux - ps -ef 命令未找到 shell 脚本
- java - 使用 Workday 的 SOAP API
- objective-c - 防止向 tableview 添加阴影以防止隐藏行在 Objective-C 或 Swift 中显示
- flutter - 将动态高度值设置为 DataTable Widget 的 dataRowHeight 属性以适应不同 Row 的内容 - #flutter
- java - 我可以配置 Spring MVC 应用程序,以便当我运行应用程序时,应该自动调用控制器或任何方法