Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

251
Visualizações
How to understand recursive generic type constraint in Unity C#?

While I understand generic types <T> and where clause for constraint, I was confused about the following code from Unity Tower Defense Template:

public abstract class Singleton<T> : MonoBehaviour where T : Singleton<T>

What's the purpose of restricting the type to be itself?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

It prevents you from doing this:

public class A
{
}

public class B : Singleton<A>
{
}

You will get a compile error. Due to the type constraint, you must write:

public class A : Singleton<A>
{
}
over 4 years ago · Santiago Trujillo Relatório

0

Off the top of my head, one possible benefit of this is allowing methods to return the specific type. This is done by fluent style methods. Another example, obviously not applicable to the example you posted, is a Copy() method that returns a copy of the object as the derived type rather than as its base type. The method signatures of the Singleton< T> class you posted likely show where it uses the T parameter and likely hint at the reason why it uses this pattern.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda