这是向下转换的一些正确用法。
我在此强烈地不同意其他人的意见,他们说使用向下转换绝对是一种代码味道,因为我相信没有其他合理的方法可以解决相应的问题。
Equals
:
class A
{
// Nothing here, but if you're a C++ programmer who dislikes object.Equals(object),
// pretend it's not there and we have abstract bool A.Equals(A) instead.
}
class B : A
{
private int x;
public override bool Equals(object other)
{
var casted = other as B; // cautious downcast (dynamic_cast in C++)
return casted != null && this.x == casted.x;
}
}
Clone
:
class A : ICloneable
{
// Again, if you dislike ICloneable, that's not the point.
// Just ignore that and pretend this method returns type A instead of object.
public virtual object Clone()
{
return this.MemberwiseClone(); // some sane default behavior, whatever
}
}
class B : A
{
private int[] x;
public override object Clone()
{
var copy = (B)base.Clone(); // known downcast (static_cast in C++)
copy.x = (int[])this.x.Clone(); // oh hey, another downcast!!
return copy;
}
}
Stream.EndRead/Write
:
class MyStream : Stream
{
private class AsyncResult : IAsyncResult
{
// ...
}
public override int EndRead(IAsyncResult other)
{
return Blah((AsyncResult)other); // another downcast (likely ~static_cast)
}
}
如果您要说这些是代码异味,则需要为它们提供更好的解决方案(即使由于不便而避免使用它们)。我认为没有更好的解决方案。