简体   繁体   English

类型传递给泛型方法

[英]Type passing to a generic method

I'm trying to do something pretty specific我正在尝试做一些非常具体的事情

public class EnableComponent <T> : ScriptableEvent
{
    public EnableComponent (GameObject body, bool state = true)
    {
        body.GetComponent<T>().enabled = state;
    }
}

Now this doesn't work, gives something like "The type 'T' cannot be used as type parameter 'T' in the generic type or method."现在这不起作用,给出类似“类型'T'不能用作泛型类型或方法中的类型参数'T'”。

I tried to do a bit of searching, and the best I found was a short discussion on why this doesn't work in java.我试着做一些搜索,我发现最好的结果是简短讨论为什么这在 java 中不起作用。

I've tried implementing the same thing by passing a Type parameter but couldn't quite figure it out.我已经尝试通过传递一个 Type 参数来实现同样的事情,但无法完全弄清楚。 I'm pretty sure this would be the way to go, just not exactly sure how to get it to work.我很确定这将是 go 的方式,只是不确定如何让它工作。

Just hoping someone has a suggestion on a way to implement the above logic.只是希望有人对实现上述逻辑的方法提出建议。

Thanks in advance.提前致谢。

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

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