下面是代码:
Base b = new Derived(); // Upcasting
// Some actions
Derived d = (Derived)b; // Downcasting 据我所知,引用就像模板,通过它你可以看到一些内存块。向上转换只会缩小模板的范围,因此无法访问与派生类一起添加的成员。而下向广播又在扩大这个模版。
问题是:由于没有引用派生的类型,所以只保留了基。到下转换发生时,GC的某些操作或活动是否会擦除或覆盖曾经包含派生成员的内存块?换句话说,降级Derived d = (Derived)b会失败吗?
发布于 2013-12-17 07:53:58
在上下文中,这是一个安全的演员。您已经创建了Derived实例,这就是为什么将派生处理为派生始终是安全的;任何GC活动都不会破坏实例的一部分。强制转换是一种处理方式(我将把实际的Derived状态仅仅看作是Base:我承诺只调用方法、属性的子集),而对自身的转换始终是安全的。
// Actual instance is derived, but I'm going to restrict
// my work with them: I've promissed not to call for "b"
// any derived methods/properties
Base b = new Derived();
// What is the actual type of "b"?
String typeName = b.GetType().Name; // <- "Derived"
// Try to convert to Derived
// This's better way to cast then (Derived) b
Derived d = b as Derived;
// Since "b" is actually Derived d will ne not null
if (Object.RefrenceEquals(null, d)) {
Console.Write("b is Derived");
}
// You can also check
if (b is Derived) {
Console.Write("b is a Derived instance.");
}发布于 2013-12-17 07:35:09
该变量指向实际对象所在的内存位置。如果您创建了一个类型为Derived的对象,则该变量指向此类型实例所在的内存位置。即使您使用的是基本类型Base,内存中的实例也是实例化的类型。因此,只要您确定b是Derived类型,下线就不会失败。
发布于 2013-12-17 07:35:31
不,它不能失去信息。但是,如果从一开始就没有这样的信息,演员们就会失败。如果b从来不是派生类型或派生类型,则会引发异常。
Base b = new b();
// Some actions
Derived d = (Derived)b; // will fail, b never was of type Derived.https://stackoverflow.com/questions/20628403
复制相似问题