【问题标题】:Convert type to another type C#将类型转换为另一种类型 C#
【发布时间】:2020-12-02 18:49:06
【问题描述】:

我想给一个带有类型参数的对象添加一个组件,但它说不能这样使用:

void AddScript<T>(GameObject self)
    {
        self.AddComponent<T>();
    }

我尝试寻找解决方案,但只找到了将一个对象转换为另一个对象的方法。我也尝试过拳击转换,就像它说的那样:

void AddScript<T>(GameObject self)
    {
        self.AddComponent<[Component]T>();
    }

但是编译器说它是一个类型,它是无效的。

那么如何将一种类型转换为另一种类型呢?

【问题讨论】:

  • 这个方法中T有什么用?
  • 试试void AddScript&lt;T&gt;(GameObject self) where T : UnityEngine.Component

标签: c# unity3d types


【解决方案1】:

您可能必须添加相同的类型约束。

void AddScript<T>(GameObject self)
  where T : UnityEngine.Component {
 // ...
}

上面的where 是一个类型约束,这意味着T 必须是继承自Component 或者是Component 的任何类型。

【讨论】:

    【解决方案2】:

    由于它告诉您必须传递 UnityEngine.Component 类型,因此您很可能必须将 T 限制为该类型:

    void AddScript<T>(GameObject self) where T : UnityEngine.Component
    {
        self.AddComponent<T>();
    }
    

    【讨论】:

      【解决方案3】:

      AddComponent 方法有一个泛型类型常量,其中 T 必须是 Component。

      您可以按如下方式更改方法签名

      void AddScript<T>(GameObject self) where T : Component
      {
          self.AddComponent<T>();
      }
      

      【讨论】:

        【解决方案4】:

        问题是您创建的类型参数T 的约束比self.AddComponent&lt;T&gt;() 的类型参数少。

        这是为 Unity 对象实现 AddComponent&lt;T&gt; 的方式:

        public T AddComponent<T>() where T : Component
        {
          return this.AddComponent(typeof (T)) as T;
        }
        

        因此,您还需要一个类型约束,它要么是 Component,要么是 Component 的派生词。

        【讨论】:

          猜你喜欢
          • 2020-12-14
          • 1970-01-01
          • 2012-03-28
          • 2023-04-06
          • 2018-06-25
          • 1970-01-01
          • 2011-09-24
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多