假设我们有一个界面:
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'.
答案 0 :(得分:5)
如果您确定:
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
的接口或两个类CustomIsocelesTriangle
(可能在不同的名称空间中),而您(或编译器)将它们混淆了。