开发者

C# Inheritance & Casting

I get the following exception:

InvalidCastException: Unable to cast object of type 'Employee' to type 'EmployeeProfile'.

I have the following code:

    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.

An EmployeeProfile is-an Employee. Not necessarily the other way around.

So this would work:

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.


All the answers are correct...just providing a no frills simple explanation...

class Employee

class Female : Employee

class Male: Employee

Just because you are an Employee does not make you a Female...


Maybe my brain is burned out, but I thought you can cast a subtype to its base type?

You are attempting to cast a basetype to its subtype. Exactly the opposite of what you say:

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


You need to use a library like Automapper . This library can fill the matched properties for an object:

Mapper.Initialize(cfg => {
    cfg.CreateMap<EmployeeProfile,Employee>();
});

EmployeeProfile prof = Mapper.Map<EmployeeProfile>(emp);


You are going the wrong direction. In your code an EmployeeProfile is a special type of Employee, not the other way around. So when you try to cast in reverse, the compiler is saying that an 'Employee' is not derived from 'EmployeeProfile'


You'll need a method in EmployeeProfile taht takes an Employee as argument and creates an EmployeeProfile.

EmployeeProfile enrichEmployee(Employee emp)
{
   EmployeeProfile empprof = new EmployeeProfile();
   empprof.property1 = emp.property1;
   empprof.property2 = emp.property2;
   empprof.property3 = emp.property3;

   return empprof;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜