Junior — Middle
Kuidas saab määrata piirangu parameetri tüübile generikus?
sobes.tech AI
Vastus AI-lt
In C#, the type parameter constraint in generics is specified using the where keyword. It allows you to specify that the type parameter must inherit from a certain class, implement an interface, be a reference or value type, have a parameterless constructor, etc.
Example:
// Constraint: T must be a class that implements IDisposable and has a parameterless constructor
public class MyClass<T> where T : class, IDisposable, new()
{
public T CreateInstance()
{
return new T();
}
}
This way, the compiler guarantees that when using MyClass with a specific T type, it satisfies the specified constraints.