我在C#中转换我的对象时遇到了一点问题,这样除了在接口中声明的方法之外,我还可以使用其他的对象方法。下面是我所说的一个简单的例子。
public interface IShape
{
void Print();
}
public class Square : IShape
{
#region IShape Members
public void Print()
{
HttpContext.Current.Response.Write("Square Print Called");
}
#endregion
public void PrintMore()
{
HttpContext.Current.Response.Write("Square Print More Called");
}
}为什么当下面的代码被调用时,我无法访问PrintMore()?
IShape s = (Square)shape;
s.PrintMore() // This is not available. only Print() is. 有什么帮助和解释会有帮助吗?
发布于 2011-11-08 23:15:22
因为当您尝试使用时,s.PrintMore() "s“的类型是IShape,所以它只知道接口函数。你需要做像这样的事情
Square s = (Square)shape;
s.PrintMore();或
((Square)shape).PrintMore(); // assuming you're positive its a Square type可以把接口想象成对象上的包装器,它只公开接口中定义的函数。它们仍然在那里,如果没有转换到适当的对象,您就无法访问它们。
https://stackoverflow.com/questions/8052594
复制相似问题