C# 测试通用IComparer
我正在尝试做一个通用的比较器,我不确定出了什么问题 比较器代码:C# 测试通用IComparer,c#,generics,inheritance,icomparer,C#,Generics,Inheritance,Icomparer,我正在尝试做一个通用的比较器,我不确定出了什么问题 比较器代码: namespace Pract_02 { public class ComparerProperty<T> : IComparer<T> { private String attribute; public ComparerProperty(String text) { attribute = text;
namespace Pract_02
{
public class ComparerProperty<T> : IComparer<T>
{
private String attribute;
public ComparerProperty(String text)
{
attribute = text;
}
public int Compare(T x, T y)
{
PropertyDescriptor property = GetProperty(attribute);
IComparable propX = (IComparable)property.GetValue(x);
IComparable propY = (IComparable)property.GetValue(y);
return propX.CompareTo(propY);
}
private PropertyDescriptor GetProperty(string name)
{
T item = (T)Activator.CreateInstance(typeof(T));
PropertyDescriptor propName = null;
foreach (PropertyDescriptor propDesc in TypeDescriptor.GetProperties(item))
{
if (propDesc.Name.Contains(name)) propName = propDesc;
}
return propName;
}
}
}
尝试从抽象类创建实例时发生MissingMethodException。问题在于:
T item = (T)Activator.CreateInstance(typeof(T));
您可以使用以下代码来解决问题
PropertyDescriptor propName = null;
foreach (PropertyDescriptor propDesc in TypeDescriptor.GetProperties(typeof(T)))
{
if (propDesc.Name.Contains(name)) propName = propDesc;
}
return propName;
顺便说一下,您的方法还有几个问题,例如:
- 如果尝试比较不存在的属性,则会得到NullReferenceException
- 如果您尝试比较null属性,您也会得到NullReferenceException
- 如果属性不可IComparable,则会得到InvalidCastException
T item = (T)Activator.CreateInstance(typeof(T));
您可以使用以下代码来解决问题
PropertyDescriptor propName = null;
foreach (PropertyDescriptor propDesc in TypeDescriptor.GetProperties(typeof(T)))
{
if (propDesc.Name.Contains(name)) propName = propDesc;
}
return propName;
顺便说一下,您的方法还有几个问题,例如:
- 如果尝试比较不存在的属性,则会得到NullReferenceException
- 如果您尝试比较null属性,您也会得到NullReferenceException
- 如果属性不可IComparable,则会得到InvalidCastException
ComparerProperty
,它试图在GetProperty
中构造一个新的车辆
实例<代码>车辆是抽象的,因此会出现异常。您不需要构造新实例来检索正在查找的属性。您正在创建一个ComparerProperty
,它尝试在GetProperty
中构造一个新的Vehicle
实例<代码>车辆是抽象的,因此会出现异常。您不需要构造新实例来检索正在查找的属性。