了解上投和下投c# [英] Understanding Up-casting and Down-casting c#

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

问题描述

因此,我试图理解c#中的向上转换和向下转换.

So I'm trying to understand up-casting and down-casting in c#.

我的问题是,此图是否正确或我仍缺少什么? 如果不正确,在哪里可以找到能正确表示该概念的图表?

My question is, is this diagram correct or am I still missing something? If its incorrect, where can I find a diagram that represents this concept correctly?

任何帮助将不胜感激.

Any help is greatly appreciated.

首先,我为混淆感到抱歉,我意识到该图不是很清楚,并且在向下转换中犯了一个错误(其中circle2仅可以访问字符串Colour,它应该可以访问所有属性). 我会尝试更好地解释我要代表的内容.

Firstly I apologize for the confusion, I realize the diagram is not very clear and that I made a mistake in the down-casting one (where circle2 only has access to string Colour, it should have access to all the properties). I'll try and explain better what I was trying to represent.

因此,这是附带的代码:

So, here is the code that would go with it:

        public class Shape 
        {
           public int Width {get;set;}
           public int Height {get;set;}
           public int X {get;set;}
           public int Y {get;set;}
           public void Draw()
           {
             //do something
           }
        }

        public class Circle : Shape 
        {
           public string Colour {get;set;}
        }
        public class Program
        {
            public static void Main(string[] args)
            {
                //Up-casting
                Circle circle = new Circle(); //object is created
                Shape shape = circle; // shape point to circle object

                //Down-casting
                Circle circle2 = (Circle)shape;
            }
        }

推荐答案

您不需要任何图表,只需把基本事实弄清楚,一切就变得清晰起来.

You don't need any diagrams, just get the basic facts down right and everything becomes crystal clear.

上下强制转换为 order ,所以让我们先弄清楚这一点:

Up and down casting presupose an order, so lets get that straight first:

在典型的类型层次结构中,我们具有以下内容:

In a typical type hierarchy we have the following:

Animal -> Vertebrate -> Mammal -> Feline -> Cat

更高或更通用的类型是Animal,最低或更通用的类型是Cat;因此,顺序就是该类型的一般性".

The higher, or more general, type is Animal and the lowest, or more specific, type is Cat; the order is therefore the "generalness" of the type.

向上投射将转换为更通用的类型,向下转换将转换为更特定的类型:

Upcasting is casting to a more general type, and down casting is casting to a more specific type:

  • 向上投射:Animal animal = new Cat();
  • 向下投射:var feline = (Feline)animal;
  • Up casting : Animal animal = new Cat();
  • Down casting: var feline = (Feline)animal;

好的,但是两个"casts"中是否真的都在进行?当我们向下或向上投射时,对对象进行了哪些更改?答案很简单.没有!完全不对对象进行任何更改.

Ok, but was is really going on in both "casts"? What changes are done to the objects when we down or up cast? The answer is rather simple; nothing! No changes whatsoever are done to the objects at all.

两个强制类型转换都是引用转换,它们可以保留身份.这意味着施法之前和施法之后的对象是完全相同的对象.顾名思义,唯一要更改的是指向对象的引用的类型;变量animalcat.

Both casts are reference conversions which are identity preserving; this means that the object before the cast and after the cast are(is) exactly the same object. As the name implies, the only thing you are changing is the type of the reference pointing to the object; the variables animal and cat.

这样做很明显:ReferenceEquals(animal, feline);将返回true.

This is made obvious by doing: ReferenceEquals(animal, feline); which will return true.

请注意,向上转换始终是隐式的,因为它始终安全Cat始终是Feline,而始终是Mammal,依此类推.另一方面,向下转换必须明确,因为不能保证它们是安全的:

Note the upcasting is always implicit, because it is always safe; a Cat is always a Feline which is always a Mammal, etc. Downcasts on the other hand have to be explicit because they are not guaranteed to be safe:

Animal animal = new Dog();
Feline feline = animal; //unsafe, can not implicitly do the conversion

编译器要求您显式执行强制转换,这是一种告诉编译器我知道我在做什么,animalFeline,请相信我"的一种方式.当然,编译器仅会部分信任您,并且仍将提供运行时保护措施以确保强制转换是可能的,否则将抛出运行时异常.在上面的代码中,强制转换显然会失败,并且您会收到运行时错误.

The compiler asks you to perform the cast explicitly, which is a way to tell the compiler "I know what I'm doing, animal is a Feline, trust me.". Of course the compiler will trust you only partially and will still provide runtime guards to make sure the cast is possible or throw a runtime exception if it isn't. In the code above, the cast will obviously fail and you will get a runtime error.

请注意,所有这些仅适用于引用类型.根据定义,值类型没有引用转换,因为您无法获取对值类型的引用.这就是为什么值类型中不允许类型差异的原因之一;没有保留身份的转换,只有类型差异中允许的转换.

Do note that all this only applies to Reference Types. Value Types, by definition, don't have reference conversions because you can't get a reference to a value type. This is one of the reasons why type variance is not allowed in value types; there are no identity preserving conversions, the only conversions allowed in type variance.

这篇关于了解上投和下投c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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