假设我们有一个接口(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'.
最佳答案
如果您确定:
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
在不同的项目或程序集中,您在实现后忘记保存和重建它ICustomShape
; - 或者,您引用了旧版本的程序集;
- 或者,您有两个名为
ICustomShape
的接口(interface)或两个类CustomIsocelesTriangle
(可能在不同的命名空间中),而您(或编译器)将它们混淆了。
关于C# - 将对象转换为接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19885712/