[英]Casting an implementation of Interface B to and implementation of Interface A
我想讓下面的代碼運行。 我想將類A的對象強制轉換為類B的對象,但是我得到一個錯誤。 理論上,A是B的一部分,所以我看不出,為什么這不起作用。
我知道,這個演員確實意味着丟失一些數據,但這正是我想要的。 有沒有辦法讓這個運行?
public class Program
{
public static void Main()
{
var b = new B();
var a = (A)b; //Error: Cannot convert type
}
}
public interface IA{}
public interface IB : IA{}
public class A : IA{}
public class B : IB{}
你可以通過多種方式解決這個問題,一個是Gilad Green在答案中說明的方式,或者也是通過實現轉換方法:
public static implicit operator A(B b)
{
//your code to convert from B to A
}
public static implicit operator B(A a)
{
//your code to convert from A to B
}
由於B實現了IA和IB,因此除非您在此答案中實現類似代碼片段,否則不能直接相互轉換。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.