[英]How to share a string between 2 C# classes
In my first class i have this Code:在我的第一堂课上,我有这个代码:
public string getUser()
{
string UserName = metroTextBox4.Text;
return UserName;
}
public string EmailAddr()
{
string Addr = metroTextBox1.Text;
return Addr;
}
And in my other class i have this code:在我的其他班级中,我有以下代码:
private async Task kka(int value)
{
var senderg = new SmtpSender(() => new SmtpClient("localhost")
{
EnableSsl = false,
DeliveryMethod = SmtpDeliveryMethod.Network,
Port = 25
});
Email.DefaultSender = senderg;
var email = await Email
.From("myEmail@example.com")
.To($"{EmailAddr()}", $"{getUser()}") //At getUser() and at EmailAddr i have the errors
.Subject("Salut")
.Body("Mersi ca mi-ai cumparat produsul, sa ai pofta!" +
$"Comanda ta a avut valoarea de {value} lei")
.SendAsync();
}
The errors are "The name 'EmailAddr' does not exist in the current context" and "The name 'getUser' does not exist in the current context"错误是“当前上下文中不存在名称‘EmailAddr’”和“当前上下文中不存在名称‘getUser’”
You will have to create an object of the first class inside the second class's method and reference the methods EmailAddr() and getUser() using that reference.您必须在第二个类的方法中创建第一个类的对象,并使用该引用引用方法 EmailAddr() 和 getUser()。
FirstClass fObj = new FirstClass();
fObj.EmailAddr();
fObj.getUser();
or as rightly mentioned in the comment by Olivier, you can pass a reference to the first class in the constructor of the second class或者正如奥利维尔在评论中正确提到的那样,您可以在第二个类的构造函数中传递对第一个类的引用
so many different approaches.这么多不同的方法。 will give you first 2 option 1 : send email as parameter to function
将为您提供第一个 2选项 1 :发送电子邮件作为函数的参数
private async Task kka(int value, string email)
option 2 : use static class to set property.选项 2 :使用静态类来设置属性。 so you can read it from other class
所以你可以从其他班级阅读它
void Main()
{
EmailAddr2.EmailAddress = EmailAddr();
TODO();
}
private void TODO()
{
EmailAddr2.EmailAddress.Dump();
}
public string EmailAddr()
{
string Addr = "my@email.com";
return Addr;
}
public static class EmailAddr2
{
public static string EmailAddress {get;set;}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.