C#,转换. [英] C#, casting.

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

问题描述

B obj1 = (B)new A();







wats actually happening here ???

推荐答案

A B 的基类(或者,B A的子类)这里.您始终可以将子类转换为基类.由于将A 的对象强制转换为B ,因此obj1 仅具有在B 类中定义的功能.

这些是Inheritance
A is a base class of B (Or, B is a sub class of A) here. You can always cast a sub class to a base class. As the object of A is being cast to B here,the obj1 will have the functionality defined within the B class only.

These are the basics of Inheritance and
<br />
Polymorphism

的基础.您可能希望先学习这些内容.

. You may wish to learn these first.


正在发生分配(如果A是B的子类).否则将引发异常(如果B是A的子类).

假设是前者-A是B的子类(因此强制转换有效),您将告诉编译器尽管我刚刚创建了" A",所以obj1实际上是" A" ",当我使用obj1时,将其视为"B".

当"B"声明一个类家族共有的行为和属性时,以及当您希望能够与该家族的任何成员一起工作而不论其实际是哪个具体成员时,这将非常有用.正如Al-Forooque所说,您正在做的是多态.
An assignment is happening (if A is a subclass of B). Or an exception is being thrown (if B is a subclass of A).

Assuming the former - that A is a subclass of B (and so the cast is valid), you''re telling the compiler that ''although I just created an ''A'', and so obj1 is really an ''A'', when I use obj1, treat it as if it were a ''B''.

This is useful when ''B'' declares behaviors and properties common to a family of classes, and when you want to be able to work with any member of that family regardless of what specific member of the family it actually is. As Al-Forooque says, what you''re doing is polymorphism.


这就是我们所说的显式强制转换操作.

对于运算符,有两种类型的强制转换:

1.隐式
2.明确

您可以将子类对象分配给它的基类,因为它已经隐式定义了对象.

但是,使用()可让您覆盖常规的赋值操作,并尝试将其强制转换为其他类型.仅当实际对象能够投射到对象时,才可以进行投射.

要了解演员表,可以看看:
http://www.abhisheksur.com/2010/07/operator-overloading- with-implicit-and.htm [ ^ ]

:rose:
This is what we call Explicit cast operation taken place.

In case of operators, there are two types of cast :

1. Implicit
2. Explicit

You can assign a child class object to its base class as it is already defined with objects implicitly.

But using () lets you to override the normal assignment operation and try to cast it to another type. The cast will be possible only when the actual object is capable to cast to the object.

To know about casts, you can have a look into :
http://www.abhisheksur.com/2010/07/operator-overloading-with-implicit-and.htm[^]

:rose:


这篇关于C#,转换.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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