Why is it that I can cast a Component class instance to an interface like:
public Component FindComponent<T>()
{
var comp = (from c in components
where typeof(T).IsAssignableFrom(c.GetType())
select c).FirstOrDefault();
return comp;
}
foreach(var a in actors)
{
IHealth health = a.FindComponent<IHealth>() as IHealth;
}
But I can't cast it inside the FindComponent()
if I do:
public T FindComponent<T>()
{
var comp = (from c in components
where typeof(T).IsAssignableFrom(c.GetType())
select c).FirstOrDefault();
return comp as T;
}
As this gives the error: The type parameter 'T' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint.
It's just easier for the user to not have to cast after the FindComponent()
. Unity 3D has a similar function and you don't have to cast after it comes back and I'm not sure how it does the cast inside FindComponent()
but I'm trying to replicate that.