[英]Casting a Generic Interface Parameter Type to Generic Class Type
I'm trying to learn about Generics, Interfaces and Polymorphism. 我正在尝试了解泛型,接口和多态性。
I am creating a Pool of objects and I want those objects to conform to the Generic Interface so I can tell them to return to their respective pools. 我正在创建一个对象池,我希望这些对象符合通用接口,以便我可以告诉它们返回各自的池。
I have created the Generic Interface that accepts a Generic Type and a Generic Class. 我创建了一个接受通用类型和通用类的通用接口。
public interface IWidgetPoolObject<T> {
void ReturnToPool();
void SetPool(T pool);
}
public class WidgetPool<T> : MonoBehaviour where T : MonoBehaviour {
private List<T> m_poolList;
public T GetObject() {
//..
}
public void PoolObject(T pooledObject) {
//..
}
}
In the below example, inside the Interface Method SetPool(T pool)
, I am trying to set the classes pool. 在下面的示例中,在接口方法
SetPool(T pool)
,我尝试设置类池。 But I am getting the can't cast to type error. 但是我得到了不能转换为类型错误。
I recognize that SomeClass
's private member var is of type WidgetPool<SomeClass>
and that SetPool is just passing in a type of SomeClass
. 我知道
SomeClass
的私有成员var是WidgetPool<SomeClass>
类型,而SetPool只是传入了SomeClass
类型。 But when I try casting m_Pool = (WidgetPool<SomeClass>) pool;
但是当我尝试转换
m_Pool = (WidgetPool<SomeClass>) pool;
that doesn't work either. 那也不起作用。
public class SomeClass : MonoBehaviour, IWidgetPoolObject<SomeClass> {
private WidgetPool<SomeClass> m_Pool;
public void ReturnToPool() {
m_Pool.PoolObject(this);
}
public void SetPool(SomeClass pool) {
m_Pool = pool; //THIS LINE
}
}
I don't know enough yet to properly search what my issue would be. 我还不了解如何正确搜索我的问题。 Any help?
有什么帮助吗?
Pool has type SomeClass
while m_Pool has type WidgetPool
... you can't cast completely different types as you can't cast an integer to an array...that would not work at runtime. 池的类型为
SomeClass
而m_Pool的类型为WidgetPool
...您不能WidgetPool
完全不同的类型,因为无法将整数WidgetPool
转换为数组...在运行时不起作用。 Maybe what you want to do is to create a new WidgetPool
of a class SomeClass
like that: 也许您想要做的是创建一个类似
SomeClass
类的新WidgetPool
:
m_Pool= new WidgetPool<SomeClass>();
m_Pool.SetPool(pool);
... that would work...it depends on what you want to do... ...会起作用...这取决于您要做什么...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.