C# - 将对象转换为接口(interface)

标签 c# .net class interface casting

假设我们有一个接口(interface):

interface ICustomShape
{
}

我们有一个类继承自 Shape 类,并实现了接口(interface):

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 */);
    

那么也许:

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

关于C# - 将对象转换为接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19885712/

相关文章:

c# - 如何在扩展/方法文件中使用 Invoke 方法?

.net - Thread.Sleep(0) 和 Thread.Yield() 之间的区别

c# - MVVM 设计 : Blocking MessageBox in ViewModel

c# - 避免 JavaScript 和 C# 中的重复逻辑

c# - Gridview 中的超链接字段(Url 导航)

c# - ASP.NET MVC3 Razor : Redirecting from Partial Views

python - 声明类变量与在 __new__ 方法中声明它相同吗?

JavaScript 类 : create and destroy elements

C++ 类访问管理

c# - 相同的文本具有不同的字节大小