[英]C# - Casting an object to an interface
假設我們有一個接口:
interface ICustomShape
{
}
我們有一個從Shape類繼承的類,並實現了接口:
public class CustomIsocelesTriangle : Shape, ICustomShape
{
}
我將如何將CustomIsocelesTriangle轉換為ICustomShape對象,以用於“接口級別”?
ICustomShape x = (ICustomShape)canvas.Children[0]; //Gives runtime error: Unable to cast object of type 'program_4.CustomIsocelesTriangle' to type 'program_4.ICustomShape'.
如果您確定:
canvas.Children[0]
返回一個CustomIsocelesTriangle
。
使用調試器進行驗證,或將類型打印到控制台:
var shape = canvas.Children[0]; Console.WriteLine(shape.GetType()); // Should print "program_4.CustomIsocelesTriangle"
你鑄造ICustomShape
(不CustomShape
)。
CustomIsocelesTriangle
實現ICustomShape
。
嘗試這樣做以驗證(它應該編譯):
ICustomShape shape = new CustomIsocelesTriangle(/* Fake arguments */);
然后也許:
CustomIsocelesTriangle
有CustomIsocelesTriangle
,並且在實現ICustomShape
之后忘記了保存和重建它; ICustomShape
接口或兩個類CustomIsocelesTriangle
(也許在不同的命名空間中),並且您(或編譯器)將它們混在一起。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.