2014-09-18 4 views
0

C#에서 작은 주소록 응용 프로그램을 만들어야합니다. 양식에 이름, 주소, 도시, 주 및 우편 번호가 입력됩니다. 저축을 저장하면 목록 상자에 들어갈 필요가 있습니다. 앱에 2 개의 맞춤 수업 (주소 및 친구)이 포함되어 있습니다. 클래스 다이어그램을 보면 Address 클래스가 Friend 클래스의 위치에 대한 데이터 유형 인 것처럼 보입니다. 친구 클래스의 데이터 유형으로 맞춤 클래스 주소를 사용할 수 있습니까? 주소 클래스에는 address, city, state, zip에 대한 필드가 있으며 friend 클래스에는 name 필드가 있습니다. Friend 클래스의 해당 필드 위치는 Address 클래스의 모든 필드에서 정보를 가져 오지만 Friend 클래스 및 목록 상자로 가져 오는 방법을 알지 못합니다. 바라기를이 질문은 너무 혼란스럽지 않습니다. 나는이 사진 부분에 대해 지금 너무 걱정하지 않는다. 작동하지 않는 폼과사용자 정의 클래스를 데이터 유형으로 사용하려면 어떻게해야합니까?

namespace Friends 
{ 
public class Friend 
{ 
    #region [Fields] 
    private string _name; 
    private Address _location; 
    private string _photo; 
    #endregion 

    #region [Properties] 
    public string Name 
    { 
     get { return _name; } 
     set 
     { 
      if (value == null) 
       throw new ArgumentNullException("Name", "Please enter a name"); 
      _name = value.Trim(); 
     } 
    } 
    public Address Location { get; set } 
    public string Photo 
    { 
     get { return _photo; } 
     set { _photo = null;} 
    } 
    #endregion 
    #region Constructors 
    public Friend() 
    { 
     this.Name = String.Empty; 
     this.Photo = null; 
    } 
    public Friend(string name) 
    { 
     this.Name = name; 
     this.Photo = null; 
    } 
    public Friend(string name, Address location) 
    { 
     this.Name = name; 
     this.Location = location; 
     this.Photo = null; 
    } 
    #endregion 

    #region Methods 

    public override string ToString() 
    { 
     return this.Name + " -- " + this.Location; 
    } 
    #endregion 
    } 
} 

코드 :이 질문은 더 설명이 필요하거나 별도의 질문으로 나눌 수 필요가

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 
using PersonInfo; 


namespace Friends 
{ 
public partial class Form1 : Form 
{ 
    List<Friend> myFriend = null; 
    public Form1() 
    { 
     InitializeComponent(); 
     myFriend = new List<Friend>(); 
    } 

    private void btnSave_Click(object sender, EventArgs e) 
    { 
     Friend f = new Friend() 
     {    
      f.Name = txtName.Text, 
      f.Location.Street = txtAddress.Text, 
      f.Location.City = txtCity.Text, 
      f.Location.State = txtState.Text, 
      f.Location.Zip5 = txtZip.Text     
     };        

     lstContacts.Items.Add(f); 

    } 

    private void btnExit_Click(object sender, EventArgs e) 
    { 
     Application.Exit(); 
    } 
} 
} 

있으면 알려 주시기 바랍니다 친구 클래스입니다.

+1

당신이 우리에게 좀 더 많은 정보를 표시 할 수 있습니다 : NullReferenceException의이 발생되지 않도록하기 위해 첫 번째 생성자에 Location 속성을 초기화? 예를 들어, 코드가 현재 작동합니까? 출력은 무엇입니까? 이상한 결과가 있습니까? 너는 무엇을 기대 하느냐? –

+2

죄송합니다. 질문을 이해하지 못합니다. – DidIReallyWriteThat

+0

내 기대는 "Scott - 123 AnyPlace Park City, UT 12345"와 유사한 결과물을 목록 상자에 넣었습니다. 내 텍스트 상자에있는 정보를 Address 클래스를 통해 Field 클래스로 전달하고 내 목록 상자에서 끝내는 방법은 무엇입니까? 나는이 방식으로 2 개의 커스텀 클래스를 다루지 못했다. – ScottT

답변

-1

예, 그렇게 사용할 수 있습니다

using System.Collections.Generic; 
using System.ComponentModel.DataAnnotations; 


    public class Friend: IValidatableObject 

    { 
     [Required] 
     public string Name { get; set; } 

     public string Photo { get; set; } 

     public Address Location { get; set; } 

     public override string ToString() 
     { 
     return string.Format("{0}{1}{2}{3}", this.Location.Line1, this.Location.City, this.Location.State, this.Location.Zip); 
     } 
     public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) 
     { 
      var results = new List<ValidationResult>(); 

      var isValid = Validator.TryValidateObject(this, validationContext, results); 

      if (!isValid) 
      { 
       foreach (var validationResult in results) 
       { 
        results.Add(validationResult); 
       } 
      } 

      return results; 
     } 
    } 





public class Address 
{ 
    public string Line1 { get; set; } 
    public string City { get; set; } 
    public string State { get; set; } 
    public string Zip { get; set; } 
} 

NEET 간단합니다.

유효성 검사를 위해 유효성 검사 메서드를 호출하거나 Modelstate.isvalid를 사용할 수 있습니다.

+0

MVC를 기반으로한다고 가정했습니다. 그렇지 않습니다. 또한, 당신은 검증에 대해 이야기하는 것처럼 보입니다. 나는 그 질문에서 어디에도 보이지 않습니다. –

+0

나는 어디에서 했습니까? – codebased

+0

'ModelState.IsValid'? ... 유효성 검사는 질문과 관련이없는 것 같습니다. –

0

귀하의 질문이 명확하고 이해하기 쉽지 않습니다. 내 생각에 당신이하고 싶은 것은 관계형 방식으로 사용자의 친구 주소 정보를 얻을 수 있어야한다는 것입니다.

나는 그것을 설명하려고 노력할 것이다. 그러나 내가 당신의 질문을 정확히 이해하지 못한다면, 당신이 정확히 알고 싶은 것을 명확하게하십시오.

참고 : 코드 샘플을 짧게 유지하기 위해 자동 속성을 사용하고 있습니다.

public class Person 
{ 
    public string Name { get; set; } 
    public AddressInfo Address { get; set; } 
    public List<Person> Friends { get; set; } 

    public Person() 
    { 
     //Avoid object reference not set exception. 
     Friends = new List<Person>(); 
    } 
} 

그리고 주소를 모델링 할 수있는 AddressInfo 클래스 :

은 여기 사람 클래스입니다.

Person newRecord = new Person(); 
newRecord.Name = "John Smith"; 
newRecord.Address = new AddressInfo(); 
newRecord.Address.ZipCode = 1234; 
newRecord.Address.Address = "Sesame street."; 

을 그리고 당신은 친구로 두 사람을 연결하려는 경우, 당신은 단순히의 다른 친구 컬렉션에 그 사람을 추가

public class AddressInfo 
{ 
    public int ZipCode { get; set; } 
    public string Adress { get; set; } 
    //More fields can be added if necessary. 
} 

는 주소로 사람을 인스턴스화합니다.

Person myFriend = new Person(); 
myFriend.Name = "John Doe"; 
myFriend.Address = new AddressInfo { ZipCode = 1234, Address = "Some street..." }; 

newRecord.Friends.Add(myFriend); 

여기에 개체 간의 관계가 생기면 좋겠다. 사람의 친구를 사귈 필요가있을 때 그 사람 객체의 "친구"컬렉션을 반복하면됩니다.

Linq를 사용하는 경우 Friends 컬렉션을 쿼리 할 수도 있습니다. 예 : myPerson.Friends.Where (f => f.Name == "John Doe") FirstOrDefault();

SQL Server와 같은 데이터베이스를 사용하는 경우 ORM (http://msdn.microsoft.com/en-us/data/ef.aspx)으로 Entity Framework를 사용하거나 주소록과 같은 데스크톱 응용 프로그램의 경우 XML 파일을 사용하여 장치간에 쉽게 연락처 목록을 만들 수 있습니다.

희망이있었습니다.

또한 할 수 있습니다 (적절한 값으로) Name - AddressLine, City, Suburb, State, Postcode :

public class Address { 
    // .. other code here 

    public override string ToString() { 
     return string.Join(",", this.AddressLine, this.City, this.Suburb, this.State, this.Postcode); 
    } 
} 

이 발생합니다 :

2

당신은 너무 자신의 출력을 렌더링 할 수 있도록 Address 클래스 ToString를 재정의해야 당신의 Friend 클래스 ToString 전화 :

public class Friend { 
    // ...other code here 

    public override string ToString() { 
     return this.Name + " -- " + this.Location.ToString(); // <-- this 
    } 
} 

을 또한, 당신이 필요로하는

public Friend(string name) { 
    // .. other stuff here 
    this.Location = new Address(); 
} 
+0

아, 나는 OP가 원했던 것을 완전히 오해했다. 당신이 날 때렸어. :) – Alaminut

+1

+1 빨리 그리기보다는 대답을 게시하기 전에 설명을 요구합니다. – codenheim

+0

@SimonWhitehead 가까이오고있는 것처럼 보입니다. 내 btn_Save 클릭 f.location 시작 4 줄에 대한 "유효하지 않은 초기화 멤버 선언 자"받고있다. 그것은 그 텍스트 상자를 읽지 않고 여전히 Scott과 함께오고있는 것과 같습니다 - – ScottT

관련 문제