gpt4 book ai didi

c# - 我在滥用 C# 泛型吗?

转载 作者:太空狗 更新时间:2023-10-30 00:51:40 31 4
gpt4 key购买 nike

我倾向于严重依赖泛型,但我担心我滥用了它们。

例如,我有一个 Entity,它包含 Component 子类的字典,组件的类型是键,组件是值。例如 PositionComponentColorComponent 等。

我有分离和获取组件的方法,定义如下:

class Entity
{
Dictionary<Type, Component> components;

//...

void DetachComponent<T>()
where T : Component
{
components.Remove(typeof(T));
}

T GetComponent<T>()
where T : Component
{
return (T)components[typeof(T)];
}
}

我讨论过的替代方法是让函数使用一个参数:void DetachComponent(Type componentType),但我不喜欢像这样调用每个方法:entity.DetachComponent( typeof(ColorComponent));

这是对泛型的滥用吗?我通常对容器类执行此操作,因为使用类型作为键的键值对对我来说很有意义。

最佳答案

我看不出有什么问题。

对于 DetachComponent,使用泛型是完全没有必要的——将类型作为泛型参数传递而不是仅仅传递常规的 (Type componentType) 参数不会有任何好处。

对于 GetComponent,使用泛型允许您在编译时返回正确的类型,而无需调用代码强制转换它。在这里,使用泛型很有意义。

自从使用泛型

  • GetComponent
  • 有意义
  • 不会对 DetachComponent 造成伤害,

我认为出于一致性的原因,将它用于两者是有意义的(即,完全按照您所做的去做)。

关于c# - 我在滥用 C# 泛型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25690188/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com