C# 仅从类型变量创建派生类的实例
我正在写一个简单的网络系统。实体定义为从基类C# 仅从类型变量创建派生类的实例,c#,inheritance,casting,C#,Inheritance,Casting,我正在写一个简单的网络系统。实体定义为从基类实体派生的类。为了在网络上识别实体,我为每个实体都有一个唯一的ID,但当需要生成一个新实体时,我需要一种方法来识别要创建的实体类型(以及相应的类),因此我还为每个实体存储一个typeId public abstract class Entity { uint id; ushort typeId; //abstract stuff } 假设我有一个所有派生实体类的列表,如下所示: public List<Type&
实体派生的类。为了在网络上识别实体,我为每个实体都有一个唯一的ID,但当需要生成一个新实体时,我需要一种方法来识别要创建的实体类型(以及相应的类),因此我还为每个实体存储一个typeId
public abstract class Entity
{
uint id;
ushort typeId;
//abstract stuff
}
假设我有一个所有派生实体类的列表,如下所示:
public List<Type> entityTypes = new List<Type>
{
typeof(Entity_BeachBall)
};
这可能吗?如果没有,有更好的解决方案吗?根本不要使用这种方法
而不是考虑创建一个工厂代表字典,由Id键入。注意我们如何使用字典而不是列表,以免依赖类型ID和列表位置之间的偶然和脆弱的关联。
private static readonly Dictionary<ushort, Func<Entity>> entityFactories = new()
{
[0] = () => new Entity_BeachBall(),
// etc.
};
public static Entity GetNewEntity(ushort typeId)
{
if (!entityFactories.ContainsKey(typeId))
{
throw new ArgumentException($"Unknown typeId {typeId}", nameof(typeId));
}
return entityFactories[typeId]();
}
为什么要投否决票?它得到了一个独特而好的答案,这一事实难道不意味着它没有资格接受“无用”的否决票吗?
public static class EntityManager
{
public List<Type> entityTypes = new List<Type>
{
typeof(Entity_BeachBall)
};
public Entity GetNewEntity(ushort typeId)
{
return new entityTypes[typeId](); //something like this
}
}
private static readonly Dictionary<ushort, Func<Entity>> entityFactories = new()
{
[0] = () => new Entity_BeachBall(),
// etc.
};
public static Entity GetNewEntity(ushort typeId)
{
if (!entityFactories.ContainsKey(typeId))
{
throw new ArgumentException($"Unknown typeId {typeId}", nameof(typeId));
}
return entityFactories[typeId]();
}
public static Entity GetNewEntity(ushort typeId)
{
return typeId switch
{
0 => new Entity_BeachBall(),
// etc.
_ => throw new ArgumentException($"Unknown typeId {typeId}", nameof(typeId))
};
}