Generic restriction in C # 2

I am reading Jon skeet amazing book "C # in depth (3d version)" right now. I am stuck on p.99, dealing with a lack of contraception for generics.

class TestGenericVariance
{
    public static void Main(string[] args)
    {
        IComparer<IShape> x =new AreaComparer();
        List<Circle> circles = new List<Circle>();
        circles.Add(new Circle());
        circles.Add(new Circle());
        //The following line is invalid, Sort expects IComparer<Circle>
        circles.Sort(x);
    }

    public interface IShape
    {

    }

    public class Circle : IShape
    {

    }

    public class AreaComparer : IComparer<IShape>
    {
        public int Compare(IShape x, IShape y)
        {
            //No matter, just for the test
            return 0;
        }
    }   
}

This code does not work because the Sort method expects

    IComparer<Circle>

as the type of parameter.

One of p.99's proposed works is to make the AreaComparer class universal:

    class AreaComparer<T> : IComparer<T> where T : IShape

And then modify the non-generic AreaComparer set to get a generic movie:

    class AreaComparer : AreaComparer<IShape>

In C # 2, the code does not compile because the Sort method on circles is still waiting

    IComparer<Circle>

Did I miss something?

Note: if I go to:

    class AreaComparer : AreaComparer<Circle>

The first line of code in the main method requests an explicit conversion form

Thank you all for your help.

+4
source share
1 answer

, AreaComparer generic :

public class AreaComparer<T> : IComparer<T> where T : IShape
{
    public int Compare(T x, T y)
    {
        return x.Area.CompareTo(y.Area);
    }
}

, , :

circles.Sort(new AreaComparer<Circle>());

, , IShape Area ( p97). , .

, IShape .

+4

All Articles