从类中的类调用方法

时间:2013-11-27 15:23:20

标签: c# wpf

我不知道如何正确地写一个标题,但我的意思是制作这样的东西:

public static MusicPlayer _Player = new MusicPlayer();

_Player.Play.Song(TestPath);

其中MusicPlayer是一个类,在那个类中,我想创建类似属性或其他类的东西,我不知道如何调用它,这将有两个方法。我现在的代码:

public class MusicPlayer
{
    //Variables, Methods and Properties in MusicPlayer
    //And then Play which can have two tipes of play.
    public static class Play
    {
        //This one should be called if I want to play one song
        public static void Song(String _path)[...]

        //And this one when I want to play from list, defined in MusicPlayer class
        public static void List()[...]
    }
}

2 个答案:

答案 0 :(得分:2)

你应该这样做:

public class MusicPlayer
{
    public class Player
    {
        public static void Song(String _path)[...]
        public static void List()[...]
    }

    private Player m_player = new Player();

    public Player Play
    {
        get { return m_player; }
    }
}

这定义了Player中的MusicPlayer类。此外,它还创建了一个Player类型的成员变量,以及一个允许您使用Player 的实例从外部访问MusicPlayer实例的属性:

var mplayer = new MusicPlayer();
mplayer.Play.Song(...);

如果您不想创建MusicPlayer的实例,也可以将其设为静态:

public class MusicPlayer
{
    public class Player
    {
        public static void Song(String _path)[...]
        public static void List()[...]
    }

    private static Player m_player = new Player();

    public static Player Play
    {
        get { return m_player; }
    }
}

您现在可以使用MusicPlayer.Play.Song(...)而无需创建实例。

答案 1 :(得分:0)

你可以做那样的事情

public class MusicPlayer
{
    public MusicPlayer()
    {
        Play = new Play();
    }
    public Play Play { get; private set; }

}

public class Play
{
    //This one should be called if I want to play one song
    public void Song(String _path){}

    //And this one when I want to play from list, defined in MusicPlayer class
    public void List() { }
}

然后使用like

new MusicPlayer().Play.Song("");