【发布时间】:2013-04-25 12:45:18
【问题描述】:
假设我有以下课程:
class Animal
{
public long Id { get; set; }
public string Name { get; set; }
}
class Dog:Animal
{
public void sniffBum()
{
Console.WriteLine("sniff sniff sniff");
}
}
如果我有一个Animal 的实例,如何将其转换为Dog?
像这样的:
Animal a = new Animal();
if ( some logic to determine that this animal is a dog )
{
Dog d = (Dog)a;
d.sniffBum();
}
基本上我不能使用接口。我将永远有一个Animal 对象从我的数据库中出来。 Dog 没有比Animal 更多的参数,只有新方法。
我可以创建一个新的Dog 对象,然后传递值,(或者有一个采用Animal 类型的构造函数),但这看起来很混乱。
【问题讨论】:
-
如果所有对象都来自
Animal类型,您还需要以某种方式将类型保存在数据库中 -
拥有一个采用
Animal类型参数的构造函数一点也不混乱 IMO -
你的
Animalclass 可以修改吗?
标签: c# oop inheritance