嘿,我不得不做一些用户管理的东西,在我创建一个新用户后,我想改变他的名字,但它没有改变。我做错了什么?
private static bool TestNameSet()
{
bool ok = true;
try
{
User user = new User("Abc", "def", "efg");
user.Name = "hhhh";
ok &= user.Name == "hhhh";
ok &= user.FirstName == "def";
ok &= user.Email == "efg";
Console.WriteLine("User set name: " + (ok ? "PASSED" : "FAILED"));
}
catch (Exception exc)
{
Console.WriteLine("User set name: FAILED");
Console.WriteLine("Error: ");
Console.Write(exc.Message);
}
return ok;
}
这个我想测试名称是否已经改变
public sealed class User
{
public string _name, _firstname, _email;
public string Name
{
get
{
return _name;
}
set
{
if (_name == null)
{
throw new ArgumentNullException();
}
}
}
public string FirstName
{
//similar to name
}
public string Email
{
//similar to name
}
public User(string name, string firstname, string email)
{
if (firstname == null)
{
throw new ArgumentNullException();
}
else if (name == null)
{
throw new ArgumentNullException();
}
else if (email == null)
{
throw new ArgumentNullException();
}
_firstname = firstname;
Name=_name = name;
Email=_email = email;
}
}
如果你们能告诉我我的代码有什么问题,我会很高兴,所以不要太苛刻;)
答案 0 :(得分:2)
您没有在设置器中设置_name
,而是在测试null
的支持字段,而不是传入的值。修改:
set
{
if (_name == null)
{
throw new ArgumentNullException();
}
}
为:
set
{
if (value == null)
{
throw new ArgumentNullException();
}
_name = value;
}
一切都会好的。