-3

私はこれに対する解決策を探していましたが、困惑しています。C#でメールクライアントを作っています。私は C# を使いこなすことができますが、構文に追いつくことがあります。

ここに私の問題があります。メールのユーザー入力に基づいて smtpclient 設定を割り当てようとしています。53 行目でエラーが発生します (割り当てられていないローカル変数の使用)。

smtpclient smm = new smtpclient(s, p);

これが私のコードです:

        private void Send_Click(object sender, EventArgs e)
    {
        //Set the login info for the email
        NetworkCredential nc = new NetworkCredential(Euser.Text, Epass.Text);
        MailMessage msg = new MailMessage();

        msg.To.Add(Toemail.Text);
        msg.From = new MailAddress(Euser.Text);
        msg.Subject = Subemail.Text;
        msg.Body = body.Text;

        string s;
        int p;

        if (Euser.Text.Contains("@gmail.com") == true)
        {
            s = "smtp.gmail.com";
            p = 587;
        }
        if (Euser.Text.Contains("@yahoo.com") == true)
        {
           s = "smtp.mail.yahoo.com"; 
           p = 995;
        }
        if (Euser.Text.Contains("@live.com") == true)
        {
           s = "smtp.live.com"; 
           p = 587;
        }

        SmtpClient smm = new SmtpClient(s, p);

        smm.Credentials = nc;
        smm.EnableSsl = true;

        try
        {
            smm.Send(msg);
            MessageBox.Show("Emails Sent Successfully");
        }
        catch (Exception ex)
        {
            MessageBox.Show("There was an error sending your emails");
        }

私は正確に何を間違っていますか?このためのメソッドを作成する必要がありますか? どんな助けでも大歓迎です。

4

2 に答える 2

1

すべての状況で、変数に値を与える必要があります。今、あなたのifテストがどれも当てはまらない場合、何をし、何sになるのpでしょうか? それらは何にも設定されません。

エラーを回避するには、変数をデフォルト値で初期化するだけです。

string s = null;
int p = 0;

または、意味がある場合は、より意味のあるものを提供します。

別の方法として、 を使用して他のelseすべてをキャプチャすることもできます。ただし、ifステートメントをelse ifs に再構築する必要があります (いずれにせよ、これは良いことです。すでに一致が見つかった場合は、さらに一致するかどうかをテストし続ける必要はありません)。

if (test)
{
}
else if (test)
{
}
else if (test)
{
}
else
{
    s = null;
    p = 0;
}
于 2013-05-17T17:27:34.730 に答える