Sobes.tech
Middle

Je možné obmedziť typy, ktoré používateľ bude prenášať cez šablónu v C#?

sobes.tech AI

Odpoveď od AI

Áno, použitím obecných obmedzení (generic constraints).

public class MyGenericClass<T> where T : IMyInterface // T musí implementovať IMyInterface
{
    // ...
}

public class AnotherGenericClass<T> where T : class // T musí byť referenčný typ
{
    // ...
}

public class YetAnotherGenericClass<T> where T : struct // T musí byť hodnotový typ
{
    // ...
}

public class CombinedConstraints<T> where T : MyBaseClass, new(), IDisposable // Kombinované obmedzenia
{
    // ...
}

Typy obmedzení:

  • where T : struct: Typ musí byť hodnotový typ (ne nullable).
  • where T : class: Typ musí byť referenčný typ.
  • where T : new(): Typ musí mať verejný bezparametrický konštruktor. Toto obmedzenie nemôže byť použité súčasne s struct a class.
  • where T : BaseClass: Typ musí dediť od BaseClass alebo byť BaseClass sám.
  • where T : IInterface: Typ musí implementovať rozhranie IInterface.
  • where T : U: Typ T musí byť alebo dediť od U, kde je U iný parameter typu.

Môžu sa kombinovať viaceré obmedzenia oddelené čiarkou. Obmedzenia na základnú triedu alebo rozhranie musia byť uvedené ako prvé.