[英]C# generics type conversion Decimal to Float - “Cannot convert type 'T1?' to 'T2'”
[英]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.