【问题标题】:How to call the function of a sibling class, from a class within the other sibling class in C#如何从C#中另一个兄弟类中的类调用兄弟类的函数
【发布时间】:2016-04-11 09:52:26
【问题描述】:

我被指派通过互联网启用对房间音频系统的远程控制来升级家庭媒体系统。由于它是一个遗留系统,我无法更改大部分架构。下面是该程序的简化形式。该系统由在 Home_Media_System 对象中初始化的几个主要类组成。

class Home_Media_System
{

    Network _networkdata

    Speakers _speakers

    Lights  _lights

    Household_devices household_devices

}

class Speakers
{
    void Play_Audio();
}


class Network
{
    UdpReceiver udpReceiver
    UdpTransmitter udpTransmitter

}


class UdpReceiver
{
    void receive_audio_player_command()
    {
        if(playCommand)
            start_audio();
    }

    void start_audio()
    {
        //How do I call the Play_Audio() function in class Speakers
    }

}

class UdpTransmitter
{
    void send_response();
}

我的问题是在 Network 类的 UdpReceiver 类中接收到命令后调用 Play_Audio() 函数。我希望这能澄清问题的标题,因为很难用一句话来解释。

请注意,主类在 Home_Media_System 中初始化。现在我正在考虑使用双事件处理程序,但我想知道是否有更优雅的方法。

【问题讨论】:

  • 这个问题无法回答。这取决于您的软件的实现。
  • 听起来像委托
  • 您的课程不是公开的,因此您可能无法在主课程之外访问这些课程。

标签: c# function class call


【解决方案1】:

首先你的类和你的方法一样是私有的,要调用播放音频方法,你应该在 void 之前添加 public,相同的角色适用于所有方法,当你公开你的方法时,你必须创建你的类的实例

Speakers speakers= new Speakers();
speakers.Play_Audio();

【讨论】:

  • 感谢您的回答,但是我不能这样做,因为这将创建一个没有我想要的参数的新扬声器实例。我需要访问 Home_Media_System 中初始化的扬声器对象。
【解决方案2】:

这是你的一些糟糕的层次结构,设计肯定有问题。但为了回答这个问题,我们可以使用 C# 中的事件/委托通过父级在兄弟姐妹之间进行通信。所以我会在两个地方定义一个事件:

在您的 Network 类和 UdpReceiver 类中,并在需要时引发事件

public class Network
{
    private UdpReceiver udpReceiver;
    UdpTransmitter udpTransmitter
    public event EventHandler PlayAudioEvent;

    public void Network()
    {
        udpReceiver.PlayAudioEvent += PlayAudioEventHandler;

    }

    void PlayAudioEventHandler(object sender, EventArgs e)
    {
        if (PlayAudioEvent != null)
        {
            PlayAudioEvent(this, null);
        }
     }
}

public class UdpReceiver
{
     public event EventHandler PlayAudioEvent;
    void receive_audio_player_command()
    {
        if(playCommand)
            start_audio();
    }

    void start_audio()
    {
        //How do I call the Play_Audio() function in class Speakers
        if (PlayAudioEvent != null)
        {
            PlayAudioEvent(this, null);
        }
    }

}

public class Home_Media_System
{


        public void Home_Media_System()
        {
            _networkdata.PlayAudioEvent +=  PlayAudioEventHandler
        }

        void PlayAudioEventHandler(object sender, EventArgs e)
        {
            _speakers.PlayAudio();
        }

还将您的所有类设为公共/内部,方法也设为公共。

【讨论】:

  • 您没有取消订阅这些活动。那不是很糟糕吗?
猜你喜欢
  • 1970-01-01
  • 2021-02-25
  • 1970-01-01
  • 1970-01-01
  • 2014-07-12
  • 2015-08-28
  • 2017-08-12
  • 2015-03-13
  • 2020-07-30
相关资源
最近更新 更多