C# 中的 ArgumentNullException setter

ArgumentNullException in C# setter

我有以下代码:

private string _email;
public string email
{
    get { return _email; }
    set
    {
        try
        {
            MailAddress m = new MailAddress(email);
            this._email = email;
        }
        catch (FormatException)
        {
            throw new ArgumentException("Wrong email format");
        }
    }
}

我一直在调查,这应该是粗略的方法,但由于某种原因,总是抛出 ArgumentNullException。

你的setter是错误的,你再次使用属性 getter设置回属性,这显然是null,你需要使用value 喜欢:

try
  {
      MailAddress m = new MailAddress(value);
      this._email = value;
  }
  catch (FormatException)
  {
      throw new ArgumentException("Wrong email format");
  }

那是因为你在 setter 中使用 属性 getter 相同 属性 和 MailAddress 将给出 NullReferenceException 如果构造函数中传递的地址为空。相反,你应该使用 value

    public string email
    {
        get { return _email; }
        set
        {
            try
            {
                MailAddress m = new MailAddress(value);
                this._email = value;
            }
            catch (FormatException)
            {
                throw new ArgumentException("Wrong email format");
            }
        }
    }