简体   繁体   English

将类型转换为另一种类型 C#

[英]Convert type to another type C#

I want to add a component to an object with a type parameter, but it says it cannot be used like this:我想用类型参数向 object 添加一个组件,但它说它不能像这样使用:

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

类型“T”不能用作方法“GamObject.AddComponant()”的泛型类型中的类型参数“T”。没有从“T”到 UnityEngine.Componant 的拳击转换

I tried searching for a solution but only found ways to converting a object to another object.我尝试寻找解决方案,但只找到了将 object 转换为另一个 object 的方法。 I also tried boxing conversion like it said:我也尝试过拳击转换,就像它说的那样:

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

But the compiler said that it was a type, and it was not valid.但是编译器说它是一个类型,它是无效的。

So how do you convert a type to another type?那么如何将一种类型转换为另一种类型呢?

Since it's telling you that you have to pass a UnityEngine.Component type, you will most likely have to constrain your T to that type:由于它告诉您必须传递UnityEngine.Component类型,因此您很可能必须将T限制为该类型:

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

You have to add the same Type constraint probably.您可能必须添加相同的类型约束。

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

The where above is a type constraint which means that T must be any type that inherits from or is a Component .上面的where是一个类型约束,这意味着T必须是继承自或是Component的任何类型。

The problem is that the type argument T you have created is less constrained than the type argument of self.AddComponent<T>() .问题是您创建的类型参数Tself.AddComponent<T>()的类型参数受限制更少。

This is how AddComponent<T> is implemented for Unity objects:这是为 Unity 对象实现AddComponent<T>的方式:

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

So you will also need a type constraint that is either Component, or a derivative of Component.因此,您还需要一个类型约束,它要么是 Component,要么是 Component 的派生词。

The AddComponent method has a generic type constrant where T must be Component. AddComponent 方法有一个泛型类型常量,其中 T 必须是 Component。

You can change your method singature as follows您可以按如下方式更改方法签名

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM