我有一个产品类别:
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;
}
}
我在做 ICompare 的地方再上一堂课
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");
}
}
}
然后我调用 ProductList 类
List<Product> person;
public void Sort()
{
person.Sort(new PersonSort(PersonSort.CompareType.Email));
}
然后在 Form 中调用这个方法:
private ProductList products = new ProductList();
private void button4_Click(object sender, EventArgs e)
{
products.Sort();
}
但它显示空异常:对象引用未设置为对象的实例。** 你能帮帮我吗?如何解决?