【发布时间】:2017-09-06 17:50:43
【问题描述】:
为什么我可以将 Component 类实例转换为如下接口:
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;
}
但如果我这样做,我不能将它投射到 FindComponent() 中:
public T FindComponent<T>()
{
var comp = (from c in components
where typeof(T).IsAssignableFrom(c.GetType())
select c).FirstOrDefault();
return comp as T;
}
因为这给出了错误:类型参数“T”不能与“as”运算符一起使用,因为它没有类类型约束或“类”约束。
用户不必在FindComponent() 之后进行投射会更容易。 Unity 3D 具有类似的功能,您不必在它返回后进行投射,我不确定它如何在 FindComponent() 中进行投射,但我正在尝试复制它。
【问题讨论】:
-
在函数中添加
where T : class:public T FindComponent<T>() where T : class -
没有改变任何东西。同样的错误。
-
旁注:您可以通过以下方式简化您的第一个 linq 查询:
var comp = components.FirstOrDefault(c => typeof(T).IsAssignableFrom(c.GetType()) -
@AleksAndreev 我个人更喜欢类似 sql 的语法。
-
你的方法可以简单地看起来像:
return components.OfType<T>().FirstOrDefault();
标签: c#