0

这是另一个类中的一个方法,我想从我的主窗体中获取消息。

 string message = Encoding.ASCII.GetString(data);
 Console.WriteLine(message);

我可以以某种方式从主方法订阅此方法以在每次触发此方法时获取数据吗?

编辑:好的,这就是我的代码现在的样子:

                    } else {
                    string message = Encoding.ASCII.GetString(data);
                    DoSomething(message);
                    //Console.WriteLine(message);
                }
            } catch (Exception ex) {
                Log("Error recieving data: " + ex.ToString());
            }
        }
    }

    public delegate void SomethingHappenedHandler(string s);
    public SomethingHappenedHandler SomethingHappened = null;

    public void DoSomething(string message)
    {
        Console.WriteLine(message);
        var sh = SomethingHappened;
        if (sh == null)
        {
            sh(message);
        }
    }

在主要方法中:

            dht.dhtNode.SomethingHappened += (msg) =>
        {
            talkText.Text += "[Friend]:  " + msg + "\n\n";
        };

但它不会触发吗?我还应该怎么做才能让它发挥作用?

4

1 回答 1

0

您可以创建一个委托并订阅它。例如,

someInstance.SomethingHappened += (msg) =>
    {
        //your code
    };

public delegate void SomethingHappenedHandler(string s);
public SomethingHappenedHandler SomethingHappened = null;

public void DoSomething()
{
    string message = Encoding.ASCII.GetString(data);
    Console.WriteLine(message);

    var sh = SomethingHappened;
    if (sh != null) sh(message);
}

编辑: 要在 UI 控件中显示结果,您应该注意跨线程操作。跨线程操作无效

于 2013-08-16T19:32:28.747 回答