简体   繁体   中英

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"

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.

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

private async Task kka(int value, string email)

option 2 : use static class to set property. 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;}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM