【问题标题】:How to convert a string into a type?如何将字符串转换为类型?
【发布时间】:2021-01-25 10:35:52
【问题描述】:

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

目标是让slot.AddComponent<compToAddType>(); 正常运行

这是一个sn-p的代码:

    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'
    }

提前谢谢你。

【问题讨论】:

  • compToAdd 的确切值是多少?
  • Type.GetType() 返回您作为参数传递的对象的类型。您是否有理由要使用字符串来执行此操作?
  • 当您查看 GetType 的文档时,您会注意到程序集是如何解析的。这意味着GetType 只会在 mscorlib 和当前执行的程序集中查找类型,除非您指定#程序集限定名称。
  • 有类型构建器可以在运行时构建类:docs.microsoft.com/en-us/dotnet/api/…
  • @mjwills 它会根据您单击的按钮进行更改。在“基础”或“炮塔”之间

标签: c# unity3d


【解决方案1】:

一般见Type.AssemblyQualifiedName

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

如果您通过Assembly.GetAssembly(theKnownType)从相应的程序集中知道至少一种类型,您也可以获取程序集


也就是说,您不能使用 generic 版本 GameObject.AddComponent&lt;T&gt;(),因为泛型的类型参数需要是 compile-time constant

但是,您可以简单地使用GameObject.AddComponent(Type) 的非通用版本

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

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


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

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

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

【讨论】:

  • 我尝试使用您的代码作为参考再次编辑我的代码,它就像一个魅力,因为建议完全避免这种情况我一定会记住这一点,谢谢!
猜你喜欢
  • 2012-09-19
  • 2022-08-18
  • 2019-09-10
  • 1970-01-01
  • 2019-01-21
  • 2016-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多