Polymorphism: getting a protected member in a base class?

I am working on programming a basic media player, and I am having problems writing polymorphic code, which I learned but have never been implemented before.

There are four corresponding classes: MediaInfo, MovieInfo, Media, and Movie.

MediaInfo is an abstract base class that contains information that applies to all media files. MovieInfo inherits from MediaInfo and adds some information specific to video files.

Media is an abstract base class that represents all media files. The film is inherited from Media.

Media now contains the following line of code:

protected MediaInfo info; 

Inside Media, I have Accessors that retrieve information from MediaInfo. However, inside the Movie, I would like to have Accessors, which also extract information from MovieInfo.

So what I did in the movie:

 protected MovieInfo info; 

And inside the constructor:

 this.info = new MovieInfo(path); 

However, now I have Accessor:

 /// <summary> /// Gets the frame height of the movie file. /// </summary> public string FrameHeight { get { return this.info.FrameHeight; } } 

The problem is that FrameHeight is an accessory only available in MovieInfo. this.info is treated as MediaInfo, despite the fact that I declared it as MovieInfo, so the code generates an error.

So, to bring my problem to a more universal question: In a derived class, how do I get from a protected base variable in a base class?

Sorry if this was a bit confusing, I would be happy to clarify any obscure details.

+7
source share
2 answers

You can make the base class common in the MediaInfo type that it contains:

 public abstract class Media<T> where T : MediaInfo { protected T info; } 

You can then specify that Movie processes MovieInfo types:

 public class Movie : Media<MovieInfo> { public string FrameHeight { get { return this.info.FrameHeight; } } } 
+6
source

Here's an unconventional alternative:

 protected MovieInfo info { get { return (MovieInfo)base.info; } } 

Depending on the situation, this may or may not be better than Lee's decision. I personally like it better, just thinking in general.

+1
source

All Articles