垂头丧气,向上转型 [英] downcast and upcast

查看:151
本文介绍了垂头丧气,向上转型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的 C#的(和 OOP 的)。当我有一些code这样的:

 类Employee
{
    //一些code
}
一流的管理:员工
{
    //一些code
}

问题1 :如果我有其他code,做这样的:

 经理经理=新管理器();
   员工EMP =(雇员)经理;

下面的员工是经理,但是当我投它像一个员工这意味着我上溯造型呢?

问题2

当我有几个员工类对象和一些但不是所有的人都管理​​的,怎么能我垂头丧气在可能的地方?


解决方案

  1. 这是正确的。当你做,你正在浇铸它变成一个雇员对象,这样就意味着你不能访问任何特定的经理。


  2. 向下转型就是你把一个基类,然后试图把它变成一个更具体的类。这与使用IS和显式类型转换这样来完成:

     如果(员工是经理)
    {
        经理M =(经理)雇员;
        //用它做什么
    }


或像这样的运营商:

 经理M =(员工作为经理);
如果(M!= NULL)
{
    //用它做什么
}

如果有不清楚的地方,我会很乐意更正!

I am new to C# (and OOP). When i have some code like the following:

class Employee
{
    // some code
}


class Manager : Employee
{
    //some code
}

Question 1: if i have other code that does this:

   Manager mgr = new Manager();
   Employee emp = (Employee)mgr;

Here employee is a manager, but when i cast it like that to an Employee it means i am upcasting it?

Question 2:

When i have several Employee class objects and some but not all of them are Manager's, how can i downcast them where possible?

解决方案

  1. That is correct. When you do that you are casting it it into an "employee" object, so that means you cannot access anything manager specific.

  2. Downcasting is where you take a base class and then try and turn it into a more specific class. This can be accomplished with using is and an explicit cast like this:

    if (employee is Manager)
    {
        Manager m = (Manager)employee;
        //do something with it
    }
    

or with the as operator like this:

Manager m = (employee as Manager);
if (m != null)
{
    //do something with it
}

If anything is unclear I'll be happy to correct it!

这篇关于垂头丧气,向上转型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆