简体   繁体   English

C#-将对象投射到接口

[英]C# - Casting an object to an interface

Suppose we have an interface: 假设我们有一个接口:

interface ICustomShape
{
}

and we have a class that inherits from the Shape class, and implements the interface: 我们有一个从Shape类继承的类,并实现了接口:

public class CustomIsocelesTriangle : Shape, ICustomShape
{

}

How would I go about casting a CustomIsocelesTriangle to a ICustomShape object, for use on an "interface level?" 我将如何将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'.

If you are sure that: 如果您确定:

  1. canvas.Children[0] returns a CustomIsocelesTriangle . canvas.Children[0]返回一个CustomIsocelesTriangle
    Use the debugger to verify, or print the type to the console: 使用调试器进行验证,或将类型打印到控制台:

     var shape = canvas.Children[0]; Console.WriteLine(shape.GetType()); // Should print "program_4.CustomIsocelesTriangle" 
  2. You're casting to ICustomShape (not CustomShape ). 你铸造ICustomShape (不CustomShape )。

  3. CustomIsocelesTriangle implements ICustomShape . CustomIsocelesTriangle实现ICustomShape
    Try this to verify (it should compile): 尝试这样做以验证(它应该编译):

     ICustomShape shape = new CustomIsocelesTriangle(/* Fake arguments */); 

Then perhaps: 然后也许:

  • you have CustomIsocelesTriangle in a different project or assembly, and you forgot to save and rebuild it after you made it implement ICustomShape ; 您在其他项目或程序CustomIsocelesTriangleCustomIsocelesTriangle ,并且在实现ICustomShape之后忘记了保存和重建它;
  • or, you reference an older version of the assembly; 或者,您引用的程序集的旧版本;
  • or, you have two interfaces named ICustomShape or two classes CustomIsocelesTriangle (perhaps in different namespaces), and you (or the compiler) got them mixed up. 或者,您有两个名为ICustomShape接口或两个类CustomIsocelesTriangle (也许在不同的命名空间中),并且您(或编译器)将它们混在一起。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM