[英]How to pass a generic type into a new generic object?
I have two classes, Character and Npc which both inherit from a base class called 'Actor'. 我有两个类,Character和Npc,它们都继承自一个名为'Actor'的基类。 Consider the following two methods which are basically almost identical:
考虑以下两种基本相同的方法:
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;
}
I've tried to implement a generic method which takes in a generic Dictionary to try and merge these two methods together. 我试图实现一个泛型方法,它接受一个通用的Dictionary来尝试将这两个方法合并在一起。 (I'm not even really sure if this will work at all, it was just a naive first attempt)
(我甚至不确定这是否会起作用,这只是一个天真的第一次尝试)
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;
}
}
The commented line is where it fails. 注释行是失败的地方。
Edit: Really dumb solution to this! 编辑:真是愚蠢的解决方案! I modified the code to be all correct except for the offending line given by the answer
我修改了代码是正确的,除了答案给出的违规行
I think that the only thing you have to do is to replace this: 我认为你唯一需要做的就是替换它:
Character character = obj.AddComponent<typeof(T)>();
with this: 有了这个:
Character character = obj.AddComponent<T>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.