簡體   English   中英

C#-將對象投射到接口

[英]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'.

如果您確定:

  1. canvas.Children[0]返回一個CustomIsocelesTriangle
    使用調試器進行驗證,或將類型打印到控制台:

     var shape = canvas.Children[0]; Console.WriteLine(shape.GetType()); // Should print "program_4.CustomIsocelesTriangle" 
  2. 你鑄造ICustomShape (不CustomShape )。

  3. CustomIsocelesTriangle實現ICustomShape
    嘗試這樣做以驗證(它應該編譯):

     ICustomShape shape = new CustomIsocelesTriangle(/* Fake arguments */); 

然后也許:

  • 您在其他項目或程序CustomIsocelesTriangleCustomIsocelesTriangle ,並且在實現ICustomShape之后忘記了保存和重建它;
  • 或者,您引用的程序集的舊版本;
  • 或者,您有兩個名為ICustomShape接口或兩個類CustomIsocelesTriangle (也許在不同的命名空間中),並且您(或編譯器)將它們混在一起。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM