我在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:14:14
您的s变量的类型仍然是IShape。仅仅因为您在赋值时恰好使用了强制转换,并不会改变编译器所关心的类型。您需要:
Square s = (Square) shape;
s.PrintMore();当然,只有当shape真的是一个Square时,这才能起作用(假设没有进行自定义转换)。
我建议你在走这条路之前仔细考虑一下。通常,这样的强制转换表明您在某种程度上破坏了抽象-如果您只知道将shape作为一个IShape,那么您应该(通常)能够仅使用IShape的成员来做您需要的事情。如果不是这样,您可以:
IShape变得更强大(如果绝对必要,让它更多地接受您的代码以接受Square而不是发布于 2011-11-08 23:13:36
问题是您试图通过IShape引用访问PrintMore(),IShape引用只能看到它们声明的Print()方法。
因此,您拥有的(Square) shape类型转换没有做任何事情,因为它会立即将其存储到IShape引用中。您需要将引用本身转换为Square,方法是将其转换并存储在Square引用中,或者在调用之前进行转换:
Square s = (Square) shape;
s.PrintMore();或
IShape s = shape;
((Square)s).PrintMore();或者,如果您不确定它是否是Square,可以使用as强制转换:
Square s = shape as Square;
// will cast if it is a Square, otherwise, returns null
// this doesn't work for value types (int, struct, etc)
if (s != null)
{
s.PrintMore();
}发布于 2011-11-08 23:13:30
在IShape s = (Square)shape;行中,您告诉编译器s是一个IShape,因此只有IShape上的方法可用。
如果您使用:
Square s = (Square)shape;
s.PrintMore()那么这应该是你想要的。
这里的关键点是,当你声明一个变量时,你告诉编译器它是什么,然后你把什么对象放进那个变量中并不重要。
https://stackoverflow.com/questions/8052594
复制相似问题