不要为了重构而重构。如果您连续有以下几行代码
object o = new Building(4, "something");
Building c = o as Building;
然后无论如何将其更改为
Building o = new Building(4, "something");
但如果你有类似的东西
public void SomeMethod(object o)
{
//you absolutely need a sanity check here
Building c = o as Building;
if( c == null )
{
//throw exception perhaps
}
//this can also be rewritten as
Building b = null;
if(o != null && o is Building)
b = (Building)o;
else
//throw exception or log..etc
}
如果您尝试以下操作
if(o.GetType == typeof(Building))
Building buildingCast = o as Building;
那么你正在创建更多的冗余,事实上这会使代码的可读性降低很多,你必须做类似的事情
Building buildingCast = null; //to be able to use outside the if
if(o.GetType() == typeof(Building))
buildingCast = o as Building;
//you still end up with a null here if cast fails.
//this is the EXACT procedure of the 'as' operator anyway
//which does
Building buildingCast = o is Building ? (Building)o : (Building)null;
..当然,如果您绝对肯定,通过事先使用检查,类型是相同的,那么演员将永远不会失败。