测试通用IComparer

时间:2016-03-31 11:47:35

标签: c# generics inheritance icomparer

我正在尝试使用通用比较器,但我不确定会出现什么问题。

比较器的代码:

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;
        }
    }
}

1 个答案:

答案 0 :(得分:2)

当您尝试从抽象类Vehicle创建实例时发生MissingMethodException。问题在于:

PropertyDescriptor propName = null;
foreach (PropertyDescriptor propDesc in TypeDescriptor.GetProperties(typeof(T)))
{
    if (propDesc.Name.Contains(name)) propName = propDesc;
}

return propName;

您可以使用以下代码来解决问题

...
window.console.log(this);
return this._foo.bar;
...

顺便说一下,你的方法有另外几个问题,例如:

  • 如果您尝试比较非现有属性,则会获得NullReferenceException
  • 如果你尝试比较null属性,你也会得到NullReferenceException
  • 如果属性不是IComparable,则会出现InvalidCastException