What is the use of this generic class?

This code is compiled in visual studio, what is this use

public class MyClass<T>
   where T : MyClass<T>

Note where T : MyClass<T>

+4
source share
4 answers

This is a repeating template pattern and is usually used so that the base class can refer to its real type statically. This is done in order to maintain type safety so that the parameter or return values ​​mentioned in the base class keep track of the current type in the hierarchy, for example,

public class Animal<T> where T : Animal<T>
{
    public abstract T GiveBirth();
}

public class Cat : Animal<Cat>
{
    public override Cat GiveBirth() { return new Cat(); }
}

Without the type parameter, the base class method Animalcould determine the return type GiveBirthas Animal, which can reduce type safety for clients.

, , , , , .

public class Cat : Animal<Dog> { ... }

, , , .

public static void Feed<T>(Animal<T> animal) where T : Animal<T> { ... }
public static void Feed<T>(T animal) where T : Animal<T> { ... }
+4

. , , .

:

public class MyChild : MyClass<MyChild>

, . /... . List<Giraffe>, ; MyGeneric<T, U> where T : IComparer<U>, , T. T : MyClass<T> . , ...

abstract T Instance { get; }

... MyChild MyChild.

, , MyOtherClass : MyClass<MyChild>, MyGrandchild : MyChild, , , , .

+2

, , , . , , . , , .NET , .

abstract class AnimalBase<T> where T:AnimalBase<T>, T Clone() class Cat: AnimalBase<Cat>, var newCat = someCat.Clone(); newCat.Meow(); , var newCat = (Cat)(someCat.Clone()); newCat.Meow();. , , SiameseCat Cat, mySiameseCat.Clone(); return a SiameseCat SiameseCat AnimalBase<SiameseCat>, Cat.

, , . SiameseCat Cat IAnimal<SiameseCat>. , , , IAnimal<SiameseCat>, IAnimal<Cat> [if Cat - , ). , , .

+1

, ( ).

For example: it Node<int>turns out Node<Node<int>>.

0
source

Source: https://habr.com/ru/post/1537401/


All Articles