创建“派生类”类型的对象

发布于 2024-12-20 13:37:24 字数 503 浏览 1 评论 0原文

我最近一直在研究类继承,并且不断遇到这段特定的代码。

public class Foo {      

 public bool DoSomething() 
 { 
   return false; 
 } 
}  

public class Bar : Foo { 

 public new bool DoSomething() 
 { 
   return true; 
 } 
}  

 public cass Test { 

  public static void Main () {   

    Foo test = new Bar (); 

    Console.WriteLine (test.DoSomething ());     
  } 
} 

这里让我感到困惑的是,如果是我,我会按 Bar 类型创建一个 Bar 实例...

Bar test = new Bar();

我不明白为什么它会按照代码中的方式创建。

I've been studying class inheritance recently and I keep coming across this specific piece of code.

public class Foo {      

 public bool DoSomething() 
 { 
   return false; 
 } 
}  

public class Bar : Foo { 

 public new bool DoSomething() 
 { 
   return true; 
 } 
}  

 public cass Test { 

  public static void Main () {   

    Foo test = new Bar (); 

    Console.WriteLine (test.DoSomething ());     
  } 
} 

What confuses me here is that, if it were me I would create an instance of Bar by type Bar...

Bar test = new Bar();

I don't understand why it would be created the way it is in the code.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

人间不值得 2024-12-27 13:37:24

编写此代码可能是为了演示重写隐藏基类方法之间的区别:

在本例中,使用 实例化 Bar 对象>Foo 变量将使用基类方法 DoSomething() 并打印出 false。如果 DoSomething 方法在基类中被声明为 virtual 并在派生类中被重写,则输出将为 true,如下例所示:

public class Foo {      

 public virtual bool DoSomething() 
 { 
   return false; 
 } 
}  

public class Bar : Foo { 

 public override bool DoSomething() 
 { 
   return true; 
 } 
} 

This code was probably written to demonstrate the difference between overriding and hiding a base class method:

In this case instantiating a Bar object using a Foo variable will use the base class method DoSomething() and print out false. Had the DoSomething method been declared as virtual in the base class and been overridden in the derived class the output would be true as in the following example:

public class Foo {      

 public virtual bool DoSomething() 
 { 
   return false; 
 } 
}  

public class Bar : Foo { 

 public override bool DoSomething() 
 { 
   return true; 
 } 
} 
很酷不放纵 2024-12-27 13:37:24

在现实世界的物体中思考这些东西会更容易。

尝试考虑一辆车。您可以拥有不同品牌/型号的汽车,但每辆车都执行相同的基本功能。

您的代码可以以相同的方式处理对象。您编写的代码可以与任何汽车一起使用,但您实际上可以指定您想要的任何汽车品牌/型号:

public class Car
{
    public virtual void Drive()
    {
    }
}

public class ChevyVolt : Car
{
    public override void Drive()
    {
        // Initialize the battery and go
    }
}

public class CadillacEscalade : Car
{
    public override void Drive()
    {
        // Check to ensure you have an oil field worth of gas and go
    }
}

现在,通过这些定义...您可以创建一个负责驾驶汽车的类。什么车都没关系。您只需要担心驾驶:

public class Commuter
{
    public void GoToWork()
    {
        // Garage.PickCar() could return either ChevyVolt or an Escalade
        Car todaysRide = Garage.PickCar();

        // Now that we have a car, go to work
        todaysRide.Drive();
    }
}

It's easier to think of these things in real world objects.

Try thinking about a car. You can have different makes/models of car but each car performs the same base functionality.

Your code can work with objects in the same way. You write the code to work with any car, but you can really specify any make/model of car you want:

public class Car
{
    public virtual void Drive()
    {
    }
}

public class ChevyVolt : Car
{
    public override void Drive()
    {
        // Initialize the battery and go
    }
}

public class CadillacEscalade : Car
{
    public override void Drive()
    {
        // Check to ensure you have an oil field worth of gas and go
    }
}

Now, with those definitions...you could create a class responsible for driving the car. It wouldn't matter what car. You just have to worry about driving:

public class Commuter
{
    public void GoToWork()
    {
        // Garage.PickCar() could return either ChevyVolt or an Escalade
        Car todaysRide = Garage.PickCar();

        // Now that we have a car, go to work
        todaysRide.Drive();
    }
}
任谁 2024-12-27 13:37:24

一般来说,不会的。更现实的例子是

void DoSomethingWithAFoo(Foo f) {
    f.DoSomething();
}

在这种情况下,f 可以是 FooBar,而 DoSomethingWithAFoo 则不会不必知道或关心。

Generally, it wouldn't be. A more realistic example would be

void DoSomethingWithAFoo(Foo f) {
    f.DoSomething();
}

In this case, f could be a Foo or a Bar, and DoSomethingWithAFoo doesn't have to know or care.

春庭雪 2024-12-27 13:37:24

Bar 派生自 Foo,因此创建 Bar 实例并分配给 aa Foo 是完全有效的-参考。我怀疑您显示的示例代码仅显示 BarFoo 因此是可分配的。

Bar derives from Foo, and so it is perfectly valid to create an instance of Bar and assigned to a a Foo-reference. I suspect the example code that you have shown is merely showing that Bar is a Foo and is therefore assignable.

素染倾城色 2024-12-27 13:37:24

您可以使用不太通用的类型( Boo )分配更通用的( Foo ),这通常在利用多态性时完成。经典的例子是有 Animal、Dod 和 Cat,然后你可以说 Animal=new Dog()Animal=new Cat(),然后你可以调用虚函数它并自动调用适当的函数。这不是你的情况,因为你将函数 DoSomething 与 new ... 重叠

You can assign a more generic (Foo) with a less generic type ( Boo ) this is usually done when you leverage the polymorphism. The classical example is having Animal, Dod and Cat and then you can say Animal=new Dog() or Animal=new Cat(), then you can call virtual function on it and having the proper function automatically called. This Is not your case since you are overlapping the function DoSomething with new ...

断爱 2024-12-27 13:37:24

如果您认为它只需要 Bar 实现的 Foo 定义的功能,那么它可能更有意义。 Bar 可以自由添加更多与 Bar 相关的功能。

public class Bar : Foo { 

 public new bool DoSomething() 
 { 
   return true; 
 } 

 public bool IsValid {get;}
}  

现在,调用代码只关心 Foo 定义的抽象,因此,尽管您正在创建 Bar,您获得由Foo (只是 DoSomething),因此不是我刚刚定义的 Bar.IsValid 功能。

If you consider that it only wants the functionality defined by Foo that Bar implements, it might make more sense. Bar is free to add more functionality related to whatever Bar is.

public class Bar : Foo { 

 public new bool DoSomething() 
 { 
   return true; 
 } 

 public bool IsValid {get;}
}  

Now the calling code only cares about the abstraction defined by Foo so, despite the fact you are creating Bar, you only get the contract defined by Foo (just DoSomething) and therefore not Bar.IsValid functionality I just defined.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文