从另外两个抽象类构造一个抽象类。例如
public abstract class PlayerBase
{
public bool IsPlaying { get; set; }
public abstract void Play();
}
public abstract class VideoPlayerBase : PlayerBase
{
public abstract void Rotate();
}
public abstract class AudioPlayerBase : PlayerBase
{
public abstract void Mute();
}
我想要的是使用另外两个(VideoPlayerBase,AudioPlayerBase)抽象类来构建一个新的VedioAudioPlayerBase抽象类,而不需要太多的返工。
public abstract class VedioAudioPlayerBase
{
}
由于
答案 0 :(得分:2)
C#不支持多重继承类,但 支持多种接口实现。
所以你可以做的是将适当的方法提取到IVideoPlayer
和IAudioPlayer
接口中,然后编写一个实现这两者的类。
不幸的是,这意味着您无法继承任何实现。
但是,您可以将音频和视频逻辑封装在实现IVideoPlayer和IAudioPlayer的类中,并将它们用作AudioVideoPlayer类的实现:
public interface IPlayer
{
bool IsPlaying
{
get;
set;
}
void Play();
}
public interface IVideoPlayer: IPlayer
{
void Rotate();
}
public interface IAudioPlayer: IPlayer
{
void Mute();
}
public interface IAudioVideoPlayer: IVideoPlayer, IAudioPlayer
{
}
public abstract class PlayerBase: IPlayer
{
public bool IsPlaying
{
get;
set;
}
public abstract void Play();
}
public abstract class VideoPlayerBase: PlayerBase, IVideoPlayer
{
public abstract void Rotate();
}
public abstract class AudioPlayerBase: PlayerBase, IAudioPlayer
{
public abstract void Mute();
}
public class VideoPlayer: VideoPlayerBase
{
public override void Play()
{
Console.WriteLine("VideoPlayerBaseImpl:Play()");
}
public override void Rotate()
{
Console.WriteLine("VideoPlayerBaseImpl:Rotate()");
}
}
public class AudioPlayer : AudioPlayerBase
{
public override void Play()
{
Console.WriteLine("AudioPlayerBaseImpl:Play()");
}
public override void Mute()
{
Console.WriteLine("AudioPlayerBaseImpl:Mute()");
}
}
public class AudioVideoPlayer: IAudioVideoPlayer
{
public void Rotate()
{
_videoPlayer.Rotate();
}
public void Mute()
{
_audioPlayer.Mute();
}
public bool IsPlaying
{
get
{
return _audioPlayer.IsPlaying && _videoPlayer.IsPlaying;
}
set
{
_audioPlayer.IsPlaying = value;
_videoPlayer.IsPlaying = value;
}
}
public void Play()
{
_audioPlayer.Play();
_videoPlayer.Play();
}
private readonly AudioPlayer _audioPlayer = new AudioPlayer();
private readonly VideoPlayer _videoPlayer = new VideoPlayer();
}
答案 1 :(得分:0)
C#不支持多重继承实现。在这种情况下的标准方法是使用接口和组合:
public interface IPlayerBase
{
IsPlaying { get; set; }
void Play();
}
public interface IVideoPlayerBase : PlayerBase
{
void Rotate();
}
public interface IAudioPlayerBase : PlayerBase
{
void Mute();
}
public abstract class AbstractVideoPlayer : IVideoPlayerBase
{
public void Rotate() {
// implementation
}
}
public abstract class AbstractAudioPlayer : IAudioPlayerBase
{
public abstract void Mute() {
// implementation
}
}
public abstract class VedioAudioPlayerBase : IVideoPlayerBase, IAudioPlayerBase
{
IVideoPlayerBase video;
IAudioPlayerBase audio;
public void Rotate() {
video.Rotate();
}
public void Mute() {
audio.Mute();
}
}