Generic Type parameters
Please explain why this doesn't work? What is it about the constraint IPoolable<T>
that the compiler doesn't like? Is it because the generic IPoolable<T>
is really just a "template" and there is no inheritance between PoolItem
and IPollable<T>
?
In the code
public class GenericPool<TPoolable> where TPoolable : IPoolable<T>
while can't T
be interpreted as long?
Full code listing:
public interface IPoolab开发者_运维问答le<T> where T : new()
{
T PooledObject { get; }
}
public class PoolItem : IPoolable<long>
{
private readonly long _id;
public long PooledObject
{
get { return _id; }
}
}
public class GenericPool<TPoolable> where TPoolable : IPoolable<T>
{
public T Borrow()
{
var item = default(TPoolable);
return item.PooledObject;
}
public void Return(T item)
{
}
}
class Program
{
static void Main(string[] args)
{
var pool = new GenericPool<PoolItem>();
}
}
Just to be clear, I know that I can change GenericPool to
public class GenericPool<TPoolable, T> where TPoolable : IPoolable<T> where T : new()
I am not asking how to fix this code. Instead I am asking the question; why do I have to add T as a type parameter to GenericPool in the first place?
You can't use IPoolable<T>
as a constraint because the generic type parameter T
isn't known in that context. As you surmise, IPoolable<T>
is essentially a blueprint for an infinite number of types, so without binding T
to something (for example, a type parameter of the GenericPool
class) it doesn't make sense as a constraint.
The actual error message you should be getting is The type or namespace name 'T' could not be found
, which makes sense: T
isn't defined anywhere.
精彩评论