gpt4 book ai didi

c# - c#中的继承和c#中的对象创建

转载 作者:太空宇宙 更新时间:2023-11-03 18:23:33 25 4
gpt4 key购买 nike

我有如下类,一个是 SuperClass,它由 ChildClassChild1Class 继承 ScreenShot

public class SuperClass
{
public new int Superclassprop = 2;
public virtual void play()
{
Console.WriteLine("SuperClass");
}

}

public class ChildClass : SuperClass
{
public new int Childclassprop = 2;

public override void play()
{
Console.WriteLine("ChildClass");
}

}
public class Child1Class : SuperClass
{
public new int Childclassprop = 3;

public override void play()
{
Console.WriteLine("Child1Class");
}
}

现在,当我创建如下所示的对象时,我不明白它们之间有什么区别。我已经阅读了大量与此相关的博客,但我没有找到任何合理的答案,请帮助我了解这里实际发生的事情,或者向我推荐一个好的博客或文章,包括在 SO 上我可以理解这背后的整个概念为什么我们需要在实际实时使用这些概念的地方?

SuperClass obj = new SuperClass();
SuperClass obj1 = new ChildClass();

我附上了在运行时生成的 watch 屏幕截图,为什么有一个 obj1 包含所有属性,但我只能访问 SuperClassprop

在此先感谢任何帮助。

最佳答案

这是您的主题的更实际的示例:

using System;

public class Music
{
public virtual string play()
{
return "Play Music";
}
}

public class Drum : Music
{
public override string play()
{
return "Play Drums";
}
}

public class Piano : Music
{
public override string play()
{
return "Play Piano";
}
}

public class PlayMusicService
{
private readonly Music _musicContext;
public PlayMusicService(Music musicContext)
{
this._musicContext = musicContext;
}

public string PlayAlbum()
{
return _musicContext.play();
}
}


public class Program
{
public static void Main()
{
string whatPlayed = "";

Drum drums = new Drum();
PlayMusicService music1 = new PlayMusicService(new Drum());
whatPlayed = music1.PlayAlbum();
Console.WriteLine(whatPlayed);

Piano piano = new Piano();
PlayMusicService music2 = new PlayMusicService(new Piano());
whatPlayed = music2.PlayAlbum();
Console.WriteLine(whatPlayed);
}
}

输出:打鼓弹钢琴

关于c# - c#中的继承和c#中的对象创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42507425/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com