简体   繁体   English

C# 泛型强制转换

[英]C# generic cast conversion

I have a casting problem I am unable to solve :我有一个无法解决的铸造问题:

in ClassA initialize function, I want to pass 'this' as parameter, but the compiler cannot cast from ClassA<T, U> to ClassA<ClassB<U>, U> knowing that they are the same ( where T : ClassB<U> ).在 ClassA 初始化函数中,我想将“this”作为参数传递,但编译器无法从ClassA<T, U> ClassA<ClassB<U>, U>ClassA<ClassB<U>, U>知道它们是相同的( where T : ClassB<U> )。

public class ClassA<T, U> : MonoBehaviour where T : ClassB<U>
{
    public void initialize()
    {
        T item =...
        item.Initialize(this); // Cannot implicitly convert from ClassA<T, U> to ClassA<ClassB<U>, U>.
    }
}

public class ClassB<T> : MonoBehaviour
{
    public virtual void Initialize(ClassA<ClassB<T>, T> mgr, T data)
    {
        ...
    }
}

Thanks.谢谢。

Consider: Elephant : Animal ;考虑: Elephant : Animal this does not mean that List<Elephant> : List<Animal> , and you cannot cast a List<Elephant> to a List<Animal> for many reasons (including: that would let you Add(monkey) to the List<Elephant> , after casting to List<Animal> , because Monkey : Animal ).并不意味着List<Elephant> : List<Animal> ,并且出于多种原因您不能将List<Elephant>转换为List<Animal> (包括:这会让您Add(monkey)List<Elephant> ,在转换为List<Animal> ,因为Monkey : Animal )。 It is exactly the same here, conceptually.从概念上讲,这里完全相同。

This does not work for classes.这不适用于类。 It only works if ClassB was an interface with an out type parameter as follows:仅当ClassB是具有out类型参数的接口时才有效,如下所示:

public interface IInterfaceB<out T>
{
   …
}

However, an out type parameter means that you can only use the type parameter T for return values in your IInterfaceB interface members, not for parameters.但是,输出类型参数意味着您只能将类型参数T用于IInterfaceB接口成员中的返回值,而不能用于参数。

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

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