I am trying to implement clear in the following example code in Delphi 2009.
interface
...
TFoo<T : IInterface> = class(TObject)
FField : T;
procedure Clear;
end;
...
implementation
...
procedure TFoo<T>.Clear;
begin
// Line Below Results In
// E2010 Incompatible types: 'T' and 'Pointer'
FField := nil;
end;
...
I could understand the complie time error if "T" was not constrained. But since "T" must be an Interface, I would have thought this syntax would have worked.
Is there away to set FField to NIL, so the interface can be released?
Generic interfaces can inherit from non-generic interfaces if the generic interface is covariant, which means it only uses its type parameter as a return value.
Generics make a class, interface and, method, consider all (reference) types that are given dynamically as parameters. This ensures type safety. Generic class parameters are specified in angle brackets “<>” after the class name as of the instance variable. Generic constructors are the same as generic methods.
Java Generic Interface In similar way, we can create generic interfaces in java. We can also have multiple type parameters as in Map interface. Again we can provide parameterized value to a parameterized type also, for example new HashMap<String, List<String>>(); is valid.
A generic interface is primarily a normal interface like any other. It can be used to declare a variable but assigned the appropriate class. It can be returned from a method. It can be passed as argument. You pass a generic interface primarily the same way you would an interface.
Instead of nil
you must use the new Default(T)
which returns the default value for the generic parameter type. And for interfaces it is nil
procedure TFoo<T>.Clear;
begin
FField := Default(T);
end;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With