gpt4 book ai didi

c# - C# setter 中的 ArgumentNullException

转载 作者:行者123 更新时间:2023-11-30 20:20:26 25 4
gpt4 key购买 nike

我有以下代码:

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,如果构造函数中传递的 Address 为 null,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");
}
}
}

关于c# - C# setter 中的 ArgumentNullException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36809966/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com