douji1999 2016-11-21 04:27
浏览 57
已采纳

MailMessage是否需要任何设置来初始化?

In my console program, I want to send email to someone by using System.Net.Mail.MailMessage. However, I cannot initialize it :(

namespace:

using System.Net;
using System.Net.Mail;

code:

class emailHelper
{
    string to = "jane@address.com";
    string from = "ben@address.com";
    MailMessage message = new MailMessage(from, to);// errors here
}

the error message is about :

A field initializer cannot reference the non-static field, method, or property 'programA.emailHelper.from'

A field initializer cannot reference the non-static field, method, or property 'programA.emailHelper.to'

I have no idea that do I miss something to set before using MailMessage.

Any idea?

  • 写回答

3条回答 默认 最新

  • dszsajhd237437 2016-11-21 04:37
    关注

    The error message give you all the information.

    A field initializer cannot reference the non-static field, method, or property

    So if you want to make it work, you should make your string fields static. Which I doubt is what you want.

    class emailHelper
    {
        static string to = "jane@address.com";
        static string from = "ben@address.com";
        MailMessage message = new MailMessage(from, to);// errors here
    }
    

    Like I said this is not what you want from one helper method, to have static to and from address. Your code should look like this:

    public class EmailHelper
    {
        public string To {get; set;}
        public string From {get; set;}
        public MailMessage message {get; set;}
    
        public EmailHelper(string to, string from)
        {
             To = to;
             From = from;
    
             message = new MailMessage(from, to);
        }
    
    }
    

    In this case you have addresses which are coming out of the helper and you can create multiple MailMessage classes.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 SQL Server下载
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥15 python爬取bilibili校园招聘网站
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件
  • ¥15 不同系统编译兼容问题
  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
  • ¥30 数字电源对DSP芯片的具体要求