gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:15:20 26 4
gpt4 key购买 nike

假设我们有一个接口(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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com