2012-08-17 2 views
0

을 작동하지 않습니다 : 나는나는 목록을 정렬하고 싶지만 내가 한 제품 클래스가

 public class PersonSort : IComparer<Product> 
{ 
    public enum CompareType 
    { 
     Email 
    } 

    private CompareType compareType; 

    public PersonSort(CompareType cType) 
    { 
     this.compareType = cType; 
    } 

    public int Compare(Product x, Product y) 
    { 
     if (x == null) throw new ArgumentNullException("x"); 
     if (y == null) throw new ArgumentNullException("y"); 

     int result; 
     switch (compareType) 
     { 
      case CompareType.Email: 
       return x.Email.CompareTo(y.Email); 
      default: 
       throw new ArgumentNullException("Invalid Compare Type"); 
     } 
    } 
} 

그런 다음 ICompare 일 오전 또 하나의 클래스를 만들

 public class Product 
{ 
    private string firstname; 
    private string lastname; 
    private string email; 

    public Product() 
    { 
    } 

    public Product(string firstname, string lastname, string email) 
    { 
     this.Firstname = firstname; 
     this.Lastname = lastname; 
     this.Email = email; 
    } 

    public string Firstname 
    { 
     get 
     { 
      return firstname; 
     } 
     set 
     { 
      firstname = value; 
     } 
    } 

    public string Lastname 
    { 
     get 
     { 
      return lastname; 
     } 
     set 
     { 
      lastname = value; 
     } 
    } 

    public string Email 
    { 
     get 
     { 
      return email; 
     } 
     set 
     { 
      email = value; 
     } 
    } 

    public virtual string GetDisplayText(string sep) 
    { 
     return Firstname + sep + Lastname + sep + Email; 
    } 

} 

를 내가 양식에서 제품 목록 클래스에서 전화가

 List<Product> person; 

      public void Sort() 
    { 
     person.Sort(new PersonSort(PersonSort.CompareType.Email)); 
    } 

그런 다음이 메서드 호출 :

 private ProductList products = new ProductList(); 

      private void button4_Click(object sender, EventArgs e) 
    { 
     products.Sort(); 
    } 
하지만 나에게 널 (null) 예외를 보여 개체 참조가 개체의 인스턴스로 설정되지 않았습니다 ** 당신이 me.How이 그것을 해결하기 위해 도와주세요 수 있습니다.?

+0

어떤 문제가 발생합니까? 'Email' 값 중 하나가 null 일 수 있습니까? –

+0

어느 라인입니까? 어떤 stacktrace? –

답변

1

List<Product> person;

return x.Email.CompareTo(y.Email); 

교체? person을 목록에 추가하고 항목을 추가하거나 목록에 항목을 추가 한 다음 person 등에 할당하는 코드는 포함하지 않았습니다. 거기에 버그가 있으면 문제가 발생할 수 있습니다. null을 통과 괜찮 IComparer<T>.Compare의 문서의 일부이고, 널 (null) 인수가 다른 인수 이하로 평가하기 때문에

public int Compare(Product x, Product y) 
{ 
    if (x == null) throw new ArgumentNullException("x"); 
    if (y == null) throw new ArgumentNullException("y"); 

이 나쁜 생각이다. 나는 그것이 List<T>.Sort()과 함께 사용된다고 생각하지 않지만 비교자를 사용하는 메소드는 null이 안전하다는 것을 전제로 할 수 있습니다. 그러므로 :

public int Compare(Product x, Product y) 
{ 
    if(ReferenceEquals(x, y))//either both null or both the same instance 
    return 0; 
    if(x == null) 
    return -1; 
    if(y == null) 
    return 1; 

그와 관련된 것일 수 있습니다. Email 필드가 null의 경우

마지막으로,이 할

return x.Email.CompareTo(y.Email) 

가장 좋은 던질 수있는 것은 그 어느 일에 그것에 대해 불가능하도록 생성자와 세터의 코드를 가지고있다. 매개 변수가없는 생성자를 삭제하고, 다른 생성자와 검사기에 null 체크를 추가하여 나중에 Product이 생성 될 때 ArgumentNullException이 던져 지도록 throw합니다.

또한 비교 자에 수표를 추가 할 수 있습니다

if(x.Email == null || y.Email == null) 
    throw new Exception("Cannot compare a user with null email"); 

버그가 해결되지 않습니다 어떤하지만, 당신이 그것을 추적 도움이 될 것이다.

1

제공된 코드를 기준으로 person (ProductList)은 초기화되지 않았습니다. 즉, 질문에 예외 콜 스택을 포함 시키면 확실한 답을 얻을 수 있습니다.

List<Product> person; 

List<Product> person = new List<Product>(); 
+0

여전히 작동하지 않으며 오류가 발생하지 않습니다. – user1050667

+0

NullReferenceException이 해결됩니까? "여전히 효과가 없다"는 의미는 아닙니다. –

3

에 당신은 어딘가에 null 참조가 있습니다. 목록이 초기화되었는지 확인하십시오. 또한 Product.Email 제대로 설정되어 있습니까?

대신 StringComparer을 사용할 수 있습니다. 이 값을 주어

return StringComparer.Ordinal.Compare(x.Email, y.Email); 
+0

이미 XML 파일에 있기 때문에 Email에서 값을 전달하는 방법과 Listbox에서 해당 값을 업로드하고 그 목록을 정렬하고 싶습니까? – user1050667

+0

@ user1050667 죄송 합니다만 설치에 대해 이해하지 못했습니다. 어떤 XML 파일입니까? 어디로 가나? 무슨 Listbox? 단일 문제를 구체적으로 묻는 새로운 질문을 열고 특정 주제를 성공적으로 다룰 때 대답을 수락하십시오. – Lucero

관련 문제