[英]Call public void and private string methods with return value
In my application I want to have my main form(Form1) call a method on my UserControl(EmailControl). 在我的应用程序中,我想让我的主窗体(Form1)在UserControl(EmailControl)上调用一个方法。 Below are the three main methods I am wanting to call: 以下是我要调用的三种主要方法:
public void InitializeConnection(string hostname, int port)
{
try
{
_imapClient = new TcpClient(hostname, port);
_imapNs = _imapClient.GetStream();
_imapSw = new StreamWriter(_imapNs);
_imapSr = new StreamReader(_imapNs);
label1.Text = "*** Connected ***";
Response();
}
catch (SocketException ex)
{
Console.WriteLine(ex.Message);
}
}
, ,
public void AuthenticateUser(string username, string password)
{
_imapSw.WriteLine("$ LOGIN " + username + " " + password);
_imapSw.Flush();
label2.Text = "Logged in";
Response();
}
and 和
public string MailCount()
{
_imapSw.WriteLine("$ STATUS INBOX (messages)");
_imapSw.Flush();
string res = Response();
Match m = Regex.Match(res, "[0-9]*[0-9]");
return m.ToString();
}
To do this, I am using this on the usercontrol page: 为此,我在usercontrol页面上使用了它:
Form1.getemail += new Form1.sendtoemail(this.sendover);
and 和
public void sendover()
{
InitializeConnection("hostname", 123);
AuthenticateUser("username", "password");
MailCount();
}
Then on my main page I have 然后在我的主页上
public delegate void sendtoemail(object sender, EventArgs e);
public event sendtoemail getemail;
and 和
private void Form1_Load(object sender, EventArgs e)
{
if (this.getemail != null)
{
this.getemail(this, e);
}
}
After doing this, on my usercontrol page it is telling me that there is no overload for "sendover" matches delegate "sendtoemail", and that I need an object reference. 完成此操作后,在我的usercontrol页面上,它告诉我“ sendover”匹配委托“ sendtoemail”没有重载,并且我需要一个对象引用。 What exactly is throwing the error? 到底是什么引发错误?
The getemail
event is of type sendtoemail
, so the function you add as a handler must match that signature. getemail
事件的类型为sendtoemail
,因此您添加为处理程序的函数必须与该签名匹配。
Here are two solutions: 这是两个解决方案:
Change 更改
public void sendover()
to 至
public void sendover(object sender, EventArgs e)
or change 或改变
Form1.getemail += new Form1.sendtoemail(this.sendover);
to 至
Form1.getemail += (s, e) => sendover();
The first solution changes the signature of sendover to match the delegate type, and the second solution creates an anonymous function with the correct type which calls sendover. 第一种解决方案更改sendover的签名以匹配委托类型,第二种解决方案创建具有正确类型的匿名函数,该函数调用sendover。
Your method sendover
doesn't respect the sendtoemail
delegate's method signature: 您的方法sendover
不尊重sendtoemail
委托的方法签名:
public delegate void sendtoemail(object sender, EventArgs e); // accepts 2 parameters
Instead of the method declaration: 代替方法声明:
public void sendover() { // ...
... declare it as... ...声明为...
public void sendover(object sender, EventArgs e) { // ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.