C#继承&铸件 [英] C# Inheritance & Casting
问题描述
我有以下代码,我得到以下异常InvalidCastException:无法将'Employee'类型的对象强制转换为'EmployeeProfile'。
I have the following code, I get the following exception "InvalidCastException: Unable to cast object of type 'Employee' to type 'EmployeeProfile'."
private class Employee
{
public string Name { get; private set; }
public Employee()
{
this.Name = "employee";
}
public override string ToString()
{
return this.Name;
}
}
private class EmployeeProfile : Employee
{
public string Profile { get; private set; }
public EmployeeProfile() : base()
{
this.Profile = string.Format("{0}'s profile", this.Name);
}
public override string ToString()
{
return this.Profile;
}
}
public void RunTest()
{
Employee emp = new Employee();
EmployeeProfile prof = (EmployeeProfile)emp; // InvalidCastException here
System.Console.WriteLine(emp);
System.Console.WriteLine(prof);
}
也许我的大脑已经烧坏,但我认为你可以投下一个子类型它的基本类型?我在这里想念的是什么?也许这是一个假期...谢谢你!
Maybe my brain is burned out, but I thought you can cast a subtype to its base type? What am I missing here? Maybe it is a vacation... thank you!
推荐答案
你可以为它投一个子类型基础类型。但是您要将基类型的实例转换为子类型。
You can cast a subtype to its base type. But you are casting an instance of the base type to the subtype.
EmployeeProfile是一个Employee。不一定相反。
An EmployeeProfile is-an Employee. Not necessarily the other way around.
因此将工作:
EmployeeProfile prof = new EmployeeProfile();
Employee emp = prof;
然而,这个模型充满了糟糕的设计。员工档案不是一种特殊的员工,是吗?员工拥有个人资料更有意义。你是在这里的组合模式。
However, this model reeks of bad design. An employee profile is not a special kind of an employee, is it? It makes more sense for an employee to have a profile. You are after the composition pattern here.
这篇关于C#继承&铸件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!