【发布时间】:2020-07-16 17:45:31
【问题描述】:
我得到以下异常:
InvalidCastException:无法将“员工”类型的对象转换为类型 '员工档案'。
我有以下代码:
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);
}
也许我的大脑已经烧毁了,但我认为你可以将一个子类型转换为它的基本类型?我在这里想念什么?也许这是一个假期...谢谢!
【问题讨论】:
标签: c# inheritance