Best way to refer to my own type

前端 未结 5 1952
轻奢々
轻奢々 2021-01-03 06:02
abstract class A where T:A
{
    public event Action Event1;
}

class B : A
{
    //has a field called Action Event1;
}
         


        
5条回答
  •  南笙
    南笙 (楼主)
    2021-01-03 06:28

    The pattern you are using does not actually implement the constraint you want. Suppose you want to model "an animal can only be friendly with something of its own kind":

    abstract class Animal where T : Animal
    {
        public abstract void GetFriendly(T t);
    }
    
    class Cat : Animal
    {
        public override void GetFriendly(Cat cat) {}
    }
    

    Have we succeeded in implementing the desired constraint? No.

    class EvilDog : Animal
    {
        public override void GetFriendly(Cat cat) {}
    }
    

    Now an evil dog can be friendly with any Cat, and not friendly with other evil dogs.

    The type constraint you want is not possible in the C# type system. Try Haskell if you need this sort of constraint enforced by the type system.

    See my article on this subject for more details:

    http://blogs.msdn.com/b/ericlippert/archive/2011/02/03/curiouser-and-curiouser.aspx

提交回复
热议问题