2016-06-16 7 views
2

ユーザー管理の作業を行う必要があり、新しいユーザーを作成した後に彼の名前を変更したいが、変更はしない。私はどうしたらいいですか?私は名前をあなたたちはとても厳しすぎることがいけない、これに新たに私のコードのイムと間違っているものを私に伝えることができれば素晴らしいだろう オブジェクトがコンストラクタを使用してビルドされた後のC#プロパティの変更

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;    

    }  
} 

を変更されているかどうかをテストしたいこれで

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; 
    } 

。 )

答えて

2

あなたはセッターで_nameを設定されていない、あなたは、nullのために渡されていない値をバッキングフィールドをテストしている変更します。

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

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

、すべてがうまくなります。

+0

thx worked –

関連する問題