Question

im using a class called PriorityQueue and like the name says it should compare elements and ordain them this is the Comparer class inside priority Queue

private class DefaultComparer : IComparer
        {
            #region IComparer Members

            public int Compare(object x, object y)
            {
                #region Require

                if(!(y is IComparable))
                {
                    throw new ArgumentException(
                        "Item does not implement IComparable.");
                }

                #endregion

                IComparable a = x as IComparable;

                Debug.Assert(a != null);

                return a.CompareTo(y);
            }

            #endregion
        }

and this is what im comparing

class Coordenada : IComparable
    {
        public int x;
        public int y;
        public float heuristico;

        int IComparable.CompareTo(object coord1)
        {
            Coordenada c1 = (Coordenada)coord1;
            //Coordenada c2 = (Coordenada)coord2;

            if(c1.heuristico < heuristico)
                return 1;
            if(c1.heuristico > heuristico)
                return -1;

            return 0;
        }
    }

the error as i said in the title is: Cannot cast from source type to destination type i am aware that Coordenada and object are not the same so thats why i tried the cast and well it doesnt work any idea on what should i do?

Edit: this is how im using the priority queue thats suppossed to use the function CompareTo inside Coordenada

    Coordenada c;
    PriorityQueue cola = new PriorityQueue();

    c.x = ax;
    c.y = ay;
    c.heuristico = distancia;
    cola.Enqueue(c)

The priorityQueue is a list,im adding to that list 2-3 different Coordenada objects in a while, because im searching for the lowest number in each cycle and removing it from my list until i get where i want

Était-ce utile?

La solution

Change your CompareTo method. It is accepting object as a parameter, so it should be able to handle other things which are not Coordenada also. If object that Coordenada is being compared to, is not of same type, just return appropriate value (may be -1, 1, 0, depends on your logic). You could try like this:

int IComparable.CompareTo(object coord1)
{
    Coordenada c1 = coord1 as Coordenada;
    if (c1 == null)
        return -1;

    if(c1.heuristico < heuristico)
        return 1;
    if(c1.heuristico > heuristico)
        return -1;

    return 0;
}

It would be even better if you did not compare objects which are of completely different nature.

Autres conseils

if you are sure coord1 is Coordenada type use the explicit cast as

Coordenada c1 = coord1 as Coordenada;

throwing an InvaildCastException if c1 is null.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top