泛型类中的变量的类型错误 [英] A variable in generic class gets wrong type

查看:69
本文介绍了泛型类中的变量的类型错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下课程:

// Models:
class A {}
class B: A { }
class C: B { }

// Cache:
class AbstractCache<T> {}

// Services:
class AbstractService<T> {
    let cache = AbstractCache<T>()
}
class ServiceA<T: A>: AbstractService<T> {}
class ServiceB<T: B>: ServiceA<B> {}
class ServiceC<T: C>: ServiceB<C> {}

现在,当我这样做时:

let serviceC = ServiceC()
print(serviceC.cache.dynamicType)

我期望得到AbstractCache<C>.Type,但是我得到的是AbstractCache<B>.Type.为什么会发生这种情况,以及如何在ServiceC类实例中为cache变量获取正确的类型?

I'm expecting to get AbstractCache<C>.Type, but I get AbstractCache<B>.Type instead. Why this is happening and how do I get the correct type for cache variable in ServiceC class instance?

推荐答案

那是因为您要显式地键入ServiceAB.您应该使用T键入它,以表现出您想要的方式.

That's because you're explicitly typing ServiceA with B. You should type it with T to behave the way you want.

尝试下面的代码,它可能会按您期望的那样工作.

Try the code below, it might work as you're expecting.

// Tested @ Playground
class ServiceA<T: A>: AbstractService<T> {}
class ServiceB<T: B>: ServiceA<T> {}
class ServiceC<T: C>: ServiceB<T> {}

let serviceC = ServiceC()
print(serviceC.cache.dynamicType)

// prints "AbstractCache<C>\n"

这篇关于泛型类中的变量的类型错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆