为什么我们需要向上投射&;C#中的向下投射?

为什么我们需要向上投射&;C#中的向下投射?,c#,downcast,upcasting,C#,Downcast,Upcasting,假设我们有三个类,Shape是基类,另外两个类是圆和从基类继承的文本(Shape) Shape.cs namespace ObjectOriented { public class Shape { public int Height { get; set; } public int Width { get; set; } public int X { get; set; } public int Y { get; s

假设我们有三个类,Shape是基类,另外两个类是圆和从基类继承的文本(Shape)

Shape.cs

namespace ObjectOriented
{
    public class Shape
    {
        public int Height { get; set; }
        public int Width { get; set; }
        public int X { get; set; }
        public int Y { get; set; }

        public void Draw()
        {

        }
    }
}
Text.cs

using System;

namespace ObjectOriented
{
    public class Text : Shape
    {
        public string FontType { get; set; }
        public int FontSize { get; set; }

        public void Weirdo()
        {
            Console.WriteLine("Weird stuff");
        }

    }
}
Circle.cs

namespace ObjectOriented
{
    public class Circle : Shape
    {

    }
}
我们都知道向上转换总是成功的,并且我们从子类引用创建对基类的引用

Text txt = new Text();
Shape shape = txt //upcast
例如,向下投射可能会抛出和无效卡斯特例外

Text txt = new Text();
Shape shape = txt; //upcast
Circle c = (Circle)shape; //DownCast InvalidCastException

我感到困惑的是,我们可能需要向上/向下投射和反对的情况/案例是什么

通常对存储在列表中的对象使用向上转换。(共享基类型,甚至可以使用
对象

一件事是,
圆圈
文本
都是
形状
,但不能将
圆圈
投射到
文本
。这是因为两个类都扩展了
形状
类,并添加了不同的功能/属性

例如:
汽车
自行车
共用同一个底座
车辆
(一种用于运送人或货物的东西,尤其是在陆地上),但是
自行车
用鞍座扩展
车辆
,而
汽车
用电机扩展车辆。因此,它们不能相互“铸造”,但两者都可以被视为
Vihicle


有一些非常有用的扩展方法,用于处理类型检查:

foreach(Circle circle in shapes.OfType<Circle>())
{
    // only shapes of type Circle are iterated.
}

此循环将所有标签(在此范围内)更改为“Hi there!”

通常对存储在列表中的对象使用向上转换。(共享基类型,甚至可以使用
对象

一件事是,
圆圈
文本
都是
形状
,但不能将
圆圈
投射到
文本
。这是因为两个类都扩展了
形状
类,并添加了不同的功能/属性

例如:
汽车
自行车
共用同一个底座
车辆
(一种用于运送人或货物的东西,尤其是在陆地上),但是
自行车
用鞍座扩展
车辆
,而
汽车
用电机扩展车辆。因此,它们不能相互“铸造”,但两者都可以被视为
Vihicle


有一些非常有用的扩展方法,用于处理类型检查:

foreach(Circle circle in shapes.OfType<Circle>())
{
    // only shapes of type Circle are iterated.
}

此循环将所有标签(在此范围内)更改为“Hi there!”

您是否愿意提及使用向上投射和向下投射的真实示例?谢谢你回答得好。写得很好。你想提一下现实世界中使用上下转换的例子吗?谢谢你回答得好。写得好。
foreach(Circle circle in shapes.OfType<Circle>())
{
    // only shapes of type Circle are iterated.
}
foreach(UIElement element in this.Children)
{
    if(element is Label)
    {
        Label myLabel = (Label)element;
        myLabel.Content = "Hi there!";
    }
}