c# - 基于子类更改对象中属性的实际值
问题描述
问题:我已经以这种形式创建了对象:
Animal temporalAnimal = new Dog("Dog", "Ace","Boxer");
//Type //Name //Race
Animal 是基类, Dog 是子类。Type 和 Name 来自于 Animal,Race 来自于 Dog 类。我想将 temporalAnimal 中“Race”的值更改为“Shiba Inu”,但我无法访问该属性(它在子类上是公共的),我该如何修改他的值?
string type;
public string Type
{
get { return type; }
set { type = value; }
}
解决方案
如果您的引用是基类类型的,则您无法访问子类的属性(和方法)。您必须首先转换为子类,然后更改值:
Animal temporalAnimal = new Dog("Dog", "Ace","Boxer");
//Type //Name //Race
((Dog)temporalAnimal).Race = "Shiba Inu";
请注意,这实际上并没有改变 的类型temporalAnimal
,但它确实为您提供了它所持有的确切类型的参考。
推荐阅读
- python - Python:pmdarima,autoarima 不适用于大数据
- google-cloud-dataproc - 无法在 Dataproc 中创建集群
- r - 将多个 rshiny 应用程序合二为一
- c# - 列表c#的自定义(?)序列化
- docker - 强制删除 /usr/local/lib/docker 来修复 Homebrew 权限问题是否安全?
- java - 我的 REST API 消费者应用程序不断点击 whitelabel 错误页面
- docker - 从源代码构建 hono 时出现构建错误 - 在项目 hono-adapter-amqp-vertx 上:无法创建 docker 访问对象
- youtube-api - 从 YouTube 获取直播的更好方法?
- taskwarrior - taskwarrior,删除多个重复任务而不要求删除所有待处理
- java - 如何获得跟踪图像的角落?