我有一系列的类,每个类都有不同的属性,每个类都有一个ID(每个类型不是每个实例).
鉴于以下内容:
public class TestEntity : EntityBase {
public override ushort ID { get; } = 1;
public override void something() { do_something(); }
}
public class OtherEntity : EntityBase {
public override ushort ID { get; } = 2;
public override void something() { something_else(); }
}
Run Code Online (Sandbox Code Playgroud)
在阅读数据时,我只有ushort
:
ushort EntityId = BitConverter.ToUInt16(data.GetRange(CURRENT_POSITION + TILE_ENTITY_ID_OFFSET, TILE_ENTITY_ID_LENGTH).ToArray().Reverse().ToArray(), 0);
Run Code Online (Sandbox Code Playgroud)
如何EntityId
根据其值使用值来创建不同类型的对象?使用if
或switch
语句不是一个选项,因为将有超过200种类型.
如果我理解你的问题,这里有一种方法(有很多).
private static Dictionary<ushort, Type> TypeMap = new Dictionary<ushort, Type>()
{
{ 1, typeof(TestEntity) },
{ 2, typeof(OtherEntity) }
};
private EntityBase CreateEntity(ushort id)
{
var type = TypeMap[id];
return (EntityBase) Activator.CreateInstance(type);
}
Run Code Online (Sandbox Code Playgroud)