我试着做一个通用的比较器,我不知道哪里出了问题。
比较者的代码:
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;
}
}
}这是我的测试代码:
public void TestComparer()
{
SortedSet<Vehicle> list = new SortedSet<Vehicle>(new ComparerProperty<Vehiculo>("NumWheels"));
Car ca = new Car();
Moto mo = new Moto();
Tricycle tri = new Tricycle();
list.Add(tri);
list.Add(ca);
list.Add(mo);
IEnumerator<Vehiculo> en = list.GetEnumerator();
en.MoveNext();
Assert.AreEqual(en.Current, mo);
en.MoveNext();
Assert.AreEqual(en.Current, tri);
en.MoveNext();
Assert.AreEqual(en.Current, ca);
}问题是,当我测试它时,我收到了
"System.MissingMethodException:无法创建抽象类。“
以下是我的汽车和汽车课程的代码:
public abstract class Vehicle
{
public abstract int NumWheels
{
get;
}
}
public class Car : Vehicle
{
public override int NumWheels
{
get
{
return 4;
}
}
}发布于 2016-03-31 12:20:12
MissingMethodException发生在您试图从抽象类Vehicle创建实例时。问题是:
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;顺便说一句,您的方法还有几个问题,例如:
https://stackoverflow.com/questions/36332569
复制相似问题