Im writing a basic example of delegates usage to help explain it to me. Here is my idea.
User (object) has a playlist of songObjects.
Each songObject contains a song title and the media the song is on (MP3 or CD).
There is a MediaPlayer(object) that has two other Objects, a CDPlayer(object) and mp3Player(object)
The user inputs the songObjects list into a media player, calls the play method, and for each song the user expects back a string that lists the song name and the device it was played on.
when calling the play method, the user does not care if the song is played on a cd player or the mp3 Player, only that the song is played and they get a string back stating this, and the device it was played on.
I have some source code but its all over the place as im having trouble implementing this. Is this a valid example?
Loading
Jean PaulPosted Oct 25, 2010, 12:02 PM
namespace ConsoleApplication25
{
class Program
{
static void Main(string[] args)
{
// Create user object and create song list
User user = new User();
user.SongList = new List
user.SongList.Add(new Song { Title = "Song1", Media = "mp3" });
user.SongList.Add(new Song { Title = "Song2", Media = "cd" });
// Create mediaplayer and pass song list
MediaPlayer mediaPlayer = new MediaPlayer();
// Call the play, see the title printe on screen
mediaPlayer.Play(user.SongList, TitlePrintMethod);
// Wait for key and return
Console.ReadKey(false);
}
public static void TitlePrintMethod(string title)
{
Console.WriteLine(title);
}
}
// User Class
public class User
{
public IList
{
get;
set;
}
}
public class Song
{
public string Title
{
get;
set;
}
public string Media
{
get;
set;
}
}
public class MediaPlayer
{
public delegate void MessageDelegate(string message);
public void Play(IList
{
foreach (Song song in list)
message(song.Title);
}
}
}
Please let me know any further changes are required (or please mark as answer if it accomplishes)