从另外两个抽象类构造抽象类。例如
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
{
}谢谢
发布于 2014-03-18 08:45:15
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();
}发布于 2014-03-18 09:01:07
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();
}
}https://stackoverflow.com/questions/22474143
复制相似问题