Sobes.tech
Middle

Da li je moguće ograničiti tipove koje će korisnik prenositi putem šablona u C#?

sobes.tech АИ

Одговор од АИ

Da, koristeći ograničenja generičkih tipova (generic constraints).

public class MyGenericClass<T> where T : IMyInterface // T mora implementirati IMyInterface
{
    // ...
}

public class AnotherGenericClass<T> where T : class // T mora biti referentni tip
{
    // ...
}

public class YetAnotherGenericClass<T> where T : struct // T mora biti vrednosni tip
{
    // ...
}

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

Vrste ograničenja:

  • where T : struct: Tip mora biti vrednosni tip (ne nullable).
  • where T : class: Tip mora biti referentni tip.
  • where T : new(): Tip mora imati javni konstruktor bez parametara. Ovo ograničenje se ne može koristiti istovremeno sa struct i class.
  • where T : BaseClass: Tip mora naslediti od BaseClass ili biti BaseClass sam.
  • where T : IInterface: Tip mora implementirati interfejs IInterface.
  • where T : U: Tip T mora biti ili naslednik od U, gde je U drugi parametar tipa.

Može se kombinovati više ograničenja, razdvojene zarezom. Ograničenja na osnovnu klasu ili interfejs moraju biti navedena prvi.