C#使用构造函数生成对象后更改属性

C#使用构造函数生成对象后更改属性,c#,C#,嘿,我必须做一些用户管理的事情,在我创建了一个新用户之后,我想更改他的名字,但它没有改变。我做错了什么 private static bool TestNameSet() { bool ok = true; try { User user = new User("Abc", "def", "efg"); user.Name = "hhhh"; ok &

嘿,我必须做一些用户管理的事情,在我创建了一个新用户之后,我想更改他的名字,但它没有改变。我做错了什么

    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;            

    }     
}

如果你们能告诉我我的代码出了什么问题,那就太好了。我是新来的,所以不要太苛刻;)

您没有在setter中设置
\u name
,您正在测试支持字段的
null
,而不是传入的值。修改:

set
{
    if (_name == null)
    {
        throw new ArgumentNullException();
    }                                
}
致:

一切都会好起来的

set
{
    if (value == null)
    {
        throw new ArgumentNullException();
    }
    _name = value;                                
}