垂头丧气 [英] downcast and upcast

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

问题描述

我是 C#(和 OOP)的新手.当我有如下代码时:

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

class Employee
{
    // some code
}


class Manager : Employee
{
    //some code
}

问题 1:如果我有其他代码可以做到这一点:

Question 1: If I have other code that does this:

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

这里的 Employee 是一个 Manager,但是当我把它像这样转换成一个 Employee 时,这意味着我在向上转换它吗?

Here Employee is a Manager, but when I cast it like that to an Employee it means I am upcasting it?

问题 2:

当我有多个 Employee 类对象并且其中一些但不是全部是 Manager 的对象时,我如何尽可能降低它们?

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. 没错.当您这样做时,您将其转换为 employee 对象,这意味着您无法访问任何特定于经理的内容.

  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.

向下转换是您获取基类,然后尝试将其转换为更具体的类.这可以通过使用 is 和像这样的显式转换来完成:

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
}

或者像这样使用 as 运算符:

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天全站免登陆