我有两个类,Character和Npc,它们都继承自一个名为'Actor'的基类。考虑以下两种基本相同的方法:
public static Dictionary<uint, Npc> drawnNpcs = new Dictionary<uint, Npc>();
public static Dictionary<uint, Character> drawnCharacters = new Dictionary<uint, Character>();
private GameObject DrawCharacter(ActorWrapper actorToDraw)
{
GameObject obj;
if (Data.drawnCharacters.ContainsKey(actorToDraw.Id))
{
Character character;
Data.drawnCharacters.TryGetValue(actorToDraw.Id, out character);
obj = character.gameObject;
obj.SetActive(true);
}
else
{
obj = new GameObject("Actor");
Character character = obj.AddComponent<Character>();
character.Id = actorToDraw.Id;
Data.drawnCharacters.Add(character.Id, character);
}
return obj;
}
private GameObject DrawNpc(ActorWrapper actorToDraw)
{
GameObject obj;
if (Data.drawnNpcs.ContainsKey(actorToDraw.Id))
{
Npc npc;
Data.drawnNpcs.TryGetValue(actorToDraw.Id, out npc);
obj = npc.gameObject;
obj.SetActive(true);
}
else
{
obj = new GameObject("Actor");
Npc npc = obj.AddComponent<Npc>();
npc.Id = actorToDraw.Id;
Data.drawnNpcs.Add(npc.Id, npc);
}
return obj;
}
我试图实现一个泛型方法,它接受一个通用的Dictionary来尝试将这两个方法合并在一起。 (我甚至不确定这是否会起作用,这只是一个天真的第一次尝试)
private GameObject GetDrawnActor<T>(Dictionary<uint, T> drawnActors, ActorWrapper actorToDraw) where T : Actor
{
if (drawnActors.ContainsKey(actorToDraw.Id))
{
T actor;
drawnActors.TryGetValue(actorToDraw.Id, out actor);
GameObject obj = actor.gameObject;
obj.SetActive(true);
return obj;
}
else
{
GameObject obj = new GameObject("Actor");
var actor = obj.AddComponent<typeof(T)>(); //how do i do this??
actor.Id = actorToDraw.Id;
drawnActors.Add(actor.Id, actor);
return obj;
}
}
注释行是失败的地方。我已经看过类似的问题了,唯一的另一个选择是使用反射。有没有办法在没有反射的情况下做到这一点,而只是在设计中只有一个重构?
编辑:真是愚蠢的解决方案!我修改了代码是正确的,除了答案给出的违规行
答案 0 :(得分:5)
我认为你唯一需要做的就是替换它:
Character character = obj.AddComponent<typeof(T)>();
用这个:
Character character = obj.AddComponent<T>();