在定义的事件函数中发送参数

本文关键字:参数 函数 定义 事件 | 更新日期: 2023-09-27 17:56:38

我正在使用System.Net.NetworkInformation Ping类,我需要将一些字符串数据发送到事件函数以PingCompleted事件处理程序。我试过这个:

void ex_ping_PingCompleted(object sender, PingCompletedEventArgs e, string adress)
{
}

ex_ping.PingCompleted += (sender1, args) => ex_ping_PingCompleted(sender1, new 
PingCompletedEventArgs(), adress);

但它告诉我PingCompletedEventArgs没有构造函数。我尝试制作自己的事件参数:

public class ProgressEventArgs : PingCompletedEventArgs
{
            public string adress;
            public ProgressEventArgs(string ex_adress)
            {
                adress = ex_adress;
            }
}

同样的错误在这里。我只想知道我ping了什么地址,e.Reply.Address事件功能给了我IP,我需要站点名称。

编辑:只是自己想通了:

 ex_ping.PingCompleted += (sender1, args) => ex_ping_PingCompleted(sender1, args,adress); 
    void ex_ping_PingCompleted(object sender, PingCompletedEventArgs e,string ex_adress)        {
    }

工作正常,/关闭

在定义的事件函数中发送参数

订阅事件

 ex_ping.PingCompleted += ex_ping_PingCompleted;

并在处理程序中获取地址

void ex_ping_PingCompleted(object sender, PingCompletedEventArgs e)
{
   // verify if operation was not canceled or some error occured
   var address = e.Reply.Address;
   IPHostEntry entry = Dns.GetHostEntry(address);
   var siteName = entry.HostName;
}

你追求的是UserState属性:

void Ping()
{
    string address = "google.com";
    ex_ping.PingCompleted+=ex_ping_PingCompleted;
    ex_ping.SendAsync(address, 500, buffer, options, address);
}
void ex_ping_PingCompleted(object sender, PingCompletedEventArgs e)
{
    // Will give you the hostname
    var address = e.UserState;
}