如何将字符串转换为类型?

如何将字符串转换为类型?

问题描述:

我正在尝试将名为 compToAdd 的字符串转换为类型,但我不知道该怎么做,我尝试了近 5 个小时的谷歌搜索,现在我在这里.

Hi so I'm trying to convert a string named compToAdd into a type and im not sure how to do it, I tried googling for almost 5 hours now and here I am.

目标是使 slot.AddComponent(); 正常运行

下面是代码片段:

    public string foundationComp;
    public string turretComp;

    public void buildFoundation()
    {
        Build(foundationComp);
    }

    public void buildTurret()
    {
        Build(turretComp);
    }

    public void Build(string compToAdd)
    {      
        Type compToAddType = Type.GetType(compToAdd); //I thought this line would convert the string into a type
        slot.AddComponent<compToAddType>(); // but then I get an error here saying that compToAddType is a variable thats being used like a type..so how am I supposed to convert it?
//just note that 'slot' here have no problem and is a gameobject the problem is on the word 'compToAddType'
    }

提前致谢.

一般参见 Type.AssemblyQualifiedName.

如果您没有,则至少需要引用相关程序集,然后使用 Assembly.GetType.

If you don't have that you will need to at least have a reference to the Assembly in question and then use Assembly.GetType.

如果您通过 Assembly.GetAssembly(theKnownType)

也就是说,您不能使用 generic 版本 GameObject.AddComponent() 因为泛型的类型参数需要 compile-时间常数

That said, you can not use the generic version GameObject.AddComponent<T>() since the type-parameter of generics need to be compile-time constant!

然而,您可以简单地使用 GameObject.AddComponent 的非通用版本(类型)

You can however simply use the non-generic version of GameObject.AddComponent(Type)

public void Build(string compToAdd)
{      
    Type compToAddType = Type.GetType(compToAdd); 
    slot.AddComponent(compToAddType); 
}

(实际上甚至重载直接将string作为参数,但它已被弃用.)

(Actually there even was an overload directly taking a string as parameter but it was deprecated.)

最后,如果可能的话,我个人会完全避免它!与其依赖您的字符串是否正确,不如使用例如

Finally I personally would avoid it completely if possible! Instead of relying on your strings being correct, why not rather use e.g.

public void buildFoundation()
{
    slot.AddComponent<FoundationComponnet>();
}

public void buildTurret()
{
    slot.AddComponent<TurretComponent>();
}