Why does this generic constraint compile when it seems to have a circular reference

后端 未结 5 550
逝去的感伤
逝去的感伤 2020-12-01 19:46

I have written an extension method in csharp for an MVCContrib Html helper and was surprised at the form of the generic constraint, which on the face of it seems to circular

5条回答
  •  感情败类
    2020-12-01 20:25

    UPDATE: This question was the basis of my blog article on the 3rd of February 2011. Thanks for the great question!


    This is legal, it is not circular, and it is fairly common. I personally dislike it.

    The reasons I dislike it are:

    1) It is excessively clever; as you've discovered, clever code is hard for people unfamiliar with the intricacies of the type system to intuitively understand.

    2) It does not map well to my intuition of what a generic type "represents". I like classes to represent categories of things, and generic classes to represent parameterized categories. It is clear to me that a "list of strings" and a "list of numbers" are both kinds of lists, differing only in the type of the thing in the list. It is much less clear to me what "a TextInput of T where T is a TextInput of T" is. Don't make me think.

    3) This pattern is frequently used in an attempt to enforce a constraint in the type system which is actually not enforcable in C#. Namely this one:

    abstract class Animal where T : Animal
    {
        public abstract void MakeFriends(IEnumerable newFriends);
    }
    class Cat : Animal
    {
        public override void MakeFriends(IEnumerable newFriends) { ... }
    }
    

    The idea here is "a subclass Cat of Animal can only make friends with other Cats."

    The problem is that the desired rule is not actually enforced:

    class Tiger: Animal
    {
        public override void MakeFriends(IEnumerable newFriends) { ... }
    }
    

    Now a Tiger can make friends with Cats, but not with Tigers.

    To actually make this work in C# you'd need to do something like:

    abstract class Animal 
    {
        public abstract void MakeFriends(IEnumerable newFriends);
    }
    

    where "THISTYPE" is a magical new language feature that means "an overriding class is required to fill in its own type here".

    class Cat : Animal 
    {
        public override void MakeFriends(IEnumerable newFriends) {}
    }
    
    class Tiger: Animal
    {
        // illegal!
        public override void MakeFriends(IEnumerable newFriends) { ... }
    }
    

    Unfortunately, that's not typesafe either:

    Animal animal = new Cat();
    animal.MakeFriends(new Animal[] {new Tiger()});
    

    If the rule is "an animal can make friends with any of its kind" then an animal can make friends with animals. But a cat can only make friends with cats, not tigers! The stuff in the parameter positions has got to be valid contravariantly; in this hypothetical case we'd be requiring covariance, which isn't going to work.

    I seem to have digressed somewhat. Returning to the subject of this curiously recurring pattern: I try to only use this pattern for common, easily understood situations like the ones mentioned by other answers:

    class SortedList where T : IComparable
    

    That is, we need every T to be comparable to every other T if we have any hope of making a sorted list of them.

    To actually be flagged as circular there has to be a bona-fide circularity in dependencies:

    class C where T : U where U : T
    

    An interesting area of type theory (that at present the C# compiler handles poorly) is the area of non-circular but infinitary generic types. I have written an infinitary type detector but it did not make it into the C# 4 compiler and is not a high priority for possible hypothetical future versions of the compiler. If you're interested in some examples of infinitary types, or some examples of where the C# cycle detector messes up, see my article on that:

    http://blogs.msdn.com/b/ericlippert/archive/2008/05/07/covariance-and-contravariance-part-twelve-to-infinity-but-not-beyond.aspx

提交回复
热议问题