C# 垂头丧气
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1524197/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
downcast and upcast
提问by user184805
I am new to C#(and OOP). When I have some code like the following:
我是C#(和OOP)的新手。当我有如下代码时:
class Employee
{
// some code
}
class Manager : Employee
{
//some code
}
Question 1: If I have other code that does this:
问题 1:如果我有其他代码可以执行此操作:
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?
这Employee
是一个Manager
,但是当我像这样将Employee
它转换为 an 时,这意味着我正在向上转换它吗?
Question 2:
问题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?
当我有几个Employee
类对象并且其中一些但不是全部都是Manager
's 时,我如何尽可能降低它们?
采纳答案by RCIX
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.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 }
那是正确的。当您这样做时,您将其转换为一个
employee
对象,这意味着您无法访问任何特定于管理器的内容。向下转换是您获取基类,然后尝试将其转换为更具体的类。这可以通过使用 is 和像这样的显式转换来完成:
if (employee is Manager) { Manager m = (Manager)employee; //do something with it }
or with the as
operator like this:
或者as
像这样的操作员:
Manager m = (employee as Manager);
if (m != null)
{
//do something with it
}
If anything is unclear I'll be happy to correct it!
如果有什么不清楚的,我很乐意纠正!
回答by Preet Sangha
Upcasting(using (Employee)someInstance
) is generally easy as the compiler can tell you at compile time if a type is derived from another.
Upcasting(使用(Employee)someInstance
)通常很容易,因为编译器可以在编译时告诉您一个类型是否从另一个派生而来。
Downcastinghowever has to be done at run time generally as the compiler may not always know whether the instance in question is of the type given. C# provides two operators for this - iswhich tells you if the downcast works, and return true/false. And aswhich attempts to do the cast and returns the correct type if possible, or null if not.
然而,向下转换通常必须在运行时完成,因为编译器可能并不总是知道所讨论的实例是否属于给定的类型。C#提供了两个操作人员这一点-是它告诉你,如果垂头丧气的作品,并返回真/假。而作为它试图做演员和返回正确的类型,如果可能的话,则返回null没有。
To test if an employee is a manager:
要测试员工是否是经理:
Employee m = new Manager();
Employee e = new Employee();
if(m is Manager) Console.WriteLine("m is a manager");
if(e is Manager) Console.WriteLine("e is a manager");
You can also use this
你也可以用这个
Employee someEmployee = e as Manager;
if(someEmployee != null) Console.WriteLine("someEmployee (e) is a manager");
Employee someEmployee = m as Manager;
if(someEmployee != null) Console.WriteLine("someEmployee (m) is a manager");
回答by HOKBONG
In case you need to check each of the Employee object whether it is a Manager object, use the OfType method:
如果您需要检查每个 Employee 对象是否是 Manager 对象,请使用 OfType 方法:
List<Employee> employees = new List<Employee>();
//Code to add some Employee or Manager objects..
var onlyManagers = employees.OfType<Manager>();
foreach (Manager m in onlyManagers) {
// Do Manager specific thing..
}
回答by overcomer
- Upcastingis an operation that creates a base class reference from a subclass reference. (subclass -> superclass) (i.e. Manager -> Employee)
- Downcastingis an operation that creates a subclass reference from a base class reference. (superclass -> subclass) (i.e. Employee -> Manager)
- Upcasting是一种从子类引用创建基类引用的操作。(子类 -> 超类)(即经理 -> 员工)
- 向下转换是一种从基类引用创建子类引用的操作。(超类 -> 子类)(即员工 -> 经理)
In your case
在你的情况下
Employee emp = (Employee)mgr; //mgr is Manager
you are doing an upcasting.
你正在做一个向上转换。
An upcast always succeeds unlike a downcast that requires an explicit cast because it can potentially fail at runtime.(InvalidCastException).
与需要显式转换的向下转换不同,向上转换总是成功,因为它可能在运行时失败。(InvalidCastException)。
C# offers two operators to avoid this exception to be thrown:
C# 提供了两个运算符来避免抛出此异常:
Starting from:
从...开始:
Employee e = new Employee();
First:
第一的:
Manager m = e as Manager; // if downcast fails m is null; no exception thrown
Second:
第二:
if (e is Manager){...} // the predicate is false if the downcast is not possible
Warning: When you do an upcast you can only access to the superclass' methods, properties etc...
警告:当您进行向上转换时,您只能访问超类的方法、属性等...
回答by AutomationNerd
Upcasting and Downcasting:
上投和下投:
Upcasting: Casting from Derived-Class to Base Class Downcasting: Casting from Base Class to Derived Class
Upcasting:从派生类转换到基类 Downcasting:从基类转换到派生类
Let's understand the same as an example:
让我们以同样的方式理解:
Consider two classes Shape as My parent class and Circle as a Derived class, defined as follows:
考虑两个类 Shape 作为 My 父类和 Circle 作为派生类,定义如下:
class Shape
{
public int Width { get; set; }
public int Height { get; set; }
}
class Circle : Shape
{
public int Radius { get; set; }
public bool FillColor { get; set; }
}
Upcasting:
上行:
Shape s = new Shape();
形状 s = 新形状();
Circle c= s;
圆 c= s;
Both c and s are referencing to the same memory location, but both of them have different views i.e using "c" reference you can access all the properties of the base class and derived class as well but using "s" reference you can access properties of the only parent class.
c 和 s 都引用相同的内存位置,但它们都有不同的视图,即使用“c”引用您可以访问基类和派生类的所有属性,但使用“s”引用您可以访问属性唯一的父类。
A practical example of upcasting is Stream class which is baseclass of all types of stream reader of .net framework:
upcasting 的一个实际例子是 Stream 类,它是 .net 框架的所有类型的流阅读器的基类:
StreamReader reader = new StreamReader(new FileStreamReader());
StreamReader reader = new StreamReader(new FileStreamReader());
here, FileStreamReader() is upcasted to streadm reder.
在这里, FileStreamReader() 被向上转换为 streadm reder。
Downcasting:
向下转型:
Shape s = new Circle(); here as explained above, view of s is the only parent, in order to make it for both parent and a child we need to downcast it
形状 s = new Circle(); 这里如上所述,s 的视图是唯一的父级,为了使父级和子级都可以使用它,我们需要向下转换它
var c = (Circle) s;
var c = (圆) s;
The practical example of Downcasting is button class of WPF.
Downcasting 的实际例子是 WPF 的按钮类。
回答by Asad Patel
Answer 1 : Yes it called upcasting but the way you do it is not modern way. Upcasting can be performed implicitly you don't need any conversion. So just writing Employee emp = mgr;is enough for upcasting.
答案 1 :是的,它称为向上转换,但您这样做的方式不是现代方式。Upcasting 可以隐式执行,您不需要任何转换。所以只需写Employee emp = mgr; 足以向上投射。
Answer 2 : If you create object of Manager class we can say that manager is an employee. Because class Manager : Employeedepicts Is-A relationshipbetween Employee Class and Manager Class. So we can say that every manager is an employee.
答案 2:如果您创建 Manager 类的对象,我们可以说 manager 是一名员工。因为类 Manager : Employee描述了Employee 类和 Manager 类之间的Is-A 关系。所以我们可以说每个经理都是员工。
But if we create object of Employee class we can not say that this employee is manager because class Employeeis a class which is not inheriting any other class. So you can not directly downcast that Employee Class object to Manager Class object.
但是如果我们创建 Employee 类的对象,我们不能说这个员工是经理,因为Employee 类是一个没有继承任何其他类的类。所以你不能直接将该 Employee Class 对象向下转换为 Manager Class 对象。
So answer is, if you want to downcast from Employee Class object to Manager Class object, first you must have object of Manager Class first then you can upcast it and then you can downcast it.
所以答案是,如果你想从 Employee Class 对象向下转换到 Manager Class 对象,首先你必须先有 Manager Class 的对象,然后你可以向上转换它,然后你可以向下转换它。