如何解决将类型转换为其他类型的C#
我想使用类型参数将一个组件添加到对象,但是它说不能像这样使用它:
void AddScript<T>(GameObject self)
{
self.AddComponent<T>();
}
我尝试搜索解决方案,但只找到了将一个对象转换为另一个对象的方法。我还尝试了拳击转换,就像它说的那样:
void AddScript<T>(GameObject self)
{
self.AddComponent<[Component]T>();
}
但是编译器说这是一个类型,并且无效。
那么如何将一种类型转换为另一种类型?
解决方法
由于它告诉您必须传递UnityEngine.Component
类型,因此您很有可能必须将T
限制为该类型:
void AddScript<T>(GameObject self) where T : UnityEngine.Component
{
self.AddComponent<T>();
}
,
您可能必须添加相同的Type约束。
void AddScript<T>(GameObject self)
where T : UnityEngine.Component {
// ...
}
上面的where
是类型约束,这意味着T
必须是从Component
继承或为// 1
bool exists = requires(Sig &sig) { sig = thefunction; }
// 2
bool exists = requires(A a) { thefunction(a); }
// 2B
bool exists = requires(C &c,A a) { c.thefunction(a); }
的任何类型。
问题在于,您创建的类型参数 var a = 0;
var counts = []
// Nestling relevant values in objects for for loop
var five = {
bar: document.getElementById("fivesBar"),quantity: $("#fivesGiven").text()
}
var four = {
bar: document.getElementById("foursBar"),quantity: $("#foursGiven").text()
}
var three = {
bar: document.getElementById("threesBar"),quantity: $("#threesGiven").text()
}
var two = {
bar: document.getElementById("twosBar"),quantity: $("#twosGiven").text()
}
var one = {
bar: document.getElementById("onesBar"),quantity: $("#onesGiven").text()
}
counts.push(one,two,three,four,five);
console.log("Checking the list for counts:",counts);
// Grabbing percent complete to dynamically complete the progress bar
$(document).ready(function () {
for (b = 0; b < counts.length; b++) {
quantity = counts[b].quantity;
console.log(quantity);
quantity = parseInt(quantity)
bar = counts[b].bar;
if (a === 0) {
var width = 0;
var run = setInterval(fillratings,5);
function fillratings() {
if (width === quantity) {
clearInterval(run);
a = 0;
} else {
width++;
bar.style.width = width + "%";
console.log(width);
}
}
}
}
});
的约束比T
的类型参数要小。
这是为Unity对象实现self.AddComponent<T>()
的方式:
AddComponent<T>
因此,您还需要一个类型约束,该约束可以是Component或Component的派生类。
,AddComponent方法具有一个通用类型常量,其中T必须是Component。
您可以按以下方式更改方法名称
void AddScript<T>(GameObject self) where T : Component
{
self.AddComponent<T>();
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。