IT干货网

c#之C#继承与转换

lautakyan007 2025年05月04日 编程设计 129 0

我得到以下异常:

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); 
    } 
也许我的大脑已经精疲力尽了,但我认为您可以将一个亚型转换为其基本类型?我在这里想念什么?也许这是一个假期...谢谢!

请您参考如下方法:

您可以将子类型转换为其基本类型。但是,您正在将基本类型的实例强制转换为子类型。

EmployeeProfile是-雇员。不一定相反。

因此,这将工作:

EmployeeProfile prof = new EmployeeProfile(); 
Employee emp = prof; 

但是,此模型的外观设计不良。员工文件不是特殊的员工,对吗?对于员工来说,拥有个人资料更有意义。您在这里追求构图模式。


评论关闭
IT干货网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!