Sobes.tech
Middle

È possibile limitare i tipi che l'utente trasmetterà tramite un modello in C#?

sobes.tech AI

Risposta dell'AI

Sì, utilizzando i vincoli generici (generic constraints).

public class MyGenericClass<T> where T : IMyInterface // T deve implementare IMyInterface
{
    // ...
}

public class AnotherGenericClass<T> where T : class // T deve essere un tipo di riferimento
{
    // ...
}

public class YetAnotherGenericClass<T> where T : struct // T deve essere un tipo di valore
{
    // ...
}

public class CombinedConstraints<T> where T : MyBaseClass, new(), IDisposable // Vincoli combinati
{
    // ...
}

Tipi di vincoli:

  • where T : struct: Il tipo deve essere un tipo di valore (non nullable).
  • where T : class: Il tipo deve essere un tipo di riferimento.
  • where T : new(): Il tipo deve avere un costruttore pubblico senza parametri. Questo vincolo non può essere usato con struct e class contemporaneamente.
  • where T : BaseClass: Il tipo deve ereditare da BaseClass o essere BaseClass stesso.
  • where T : IInterface: Il tipo deve implementare l'interfaccia IInterface.
  • where T : U: Il tipo T deve essere o ereditare da U, dove U è un altro parametro di tipo.

È possibile combinare più vincoli separandoli con una virgola. I vincoli sulla classe base o sull'interfaccia devono essere indicati per primi.