C# - 将对象转换为接口

时间:2013-11-10 02:47:17

标签: c# .net class interface casting

假设我们有一个界面:

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 个答案:

答案 0 :(得分:5)

如果您确定:

  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 */);
    
  4. 然后也许:

    • 您在其他项目或程序集中有CustomIsocelesTriangle,并且在实施ICustomShape后忘记保存并重建它;
    • 或者,您引用了旧版本的程序集;
    • 或者,您有两个名为ICustomShape的接口或两个类CustomIsocelesTriangle(可能在不同的名称空间中),而您(或编译器)将它们混淆了。