繁体   English   中英

编译时错误:“无法从 B 转换为 T1”,当使用 generics、约束和 C# 中的 inheritance 时

[英]Compile time error: “Cannot convert from B to T1”, when working with generics ,constraints and inheritance in C#

我有一个 class B ,它有一个方法GetSomeB ,它返回其 class 的新实例:

public class B
{
    public B() { }
    public B GetSomeB ()
    {
        return new B();
    }
}

我有一个与 generics 一起使用的 class A。 generics 必须是 B 的 object 或从 B 继承的东西。但是我需要 A 中的属性 X 和 Y 的类型是特定的子类类型,而不仅仅是类型 B,所以我使用了 Z56B97998B338B977FFZA928 和 T2630:

class A<T1, T2>
        where T1 : B
        where T2 : B
    {
        public T1 X;
        public T2 Y;

        public A(T1 X, T2 Y)
        {
            this.X = X;
            this.Y = Y;
        }

        public A<T1, T2> GetSomeA()
        {
            return new A<T1, T2>(this.X.GetSomeB(), this.Y.GetSomeB());
        }
 }

我收到编译时错误: Cannot convert from B to T1 and Cannot convert from B to T2 from the line in GetSomeA method in class A我该如何解决这个问题?

您可以使用强制转换来修复编译错误:

public A<T1, T2> GetSomeA() 
{
      return new A<T1, T2>((T1)this.X.GetSomeB(), (T2)this.Y.GetSomeB());
}

暂无
暂无

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

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