倾斜安全

时间:2013-12-17 07:32:26

标签: c# downcast

以下是代码:

Base b = new Derived(); // Upcasting
// Some actions
Derived d = (Derived)b; // Downcasting 

据我所知,这个引用就像是模板,通过它可以看到一些内存。并且向上转换只会缩小模板,因此您无法访问使用Derived类添加的成员。而这里的向下倾斜再次扩大了模板。

问题是: 由于没有引用保存的类型的派生部分,只是Base。可能会发生GC的某些操作或活动会在转发发生时擦除或覆盖以前包含派生成员的内存块吗?换句话说,转发Derived d = (Derived)b会失败吗?

4 个答案:

答案 0 :(得分:2)

变量指向实际对象所在的内存位置。如果创建了类型为Derived的对象,则该变量指向此类型的实例所在的内存位置。即使您使用基类型Base,内存中的实例也是您实例化的类型。因此,只要您确定b属于Derived类型,就无法失败。

答案 1 :(得分:1)

在上下文中,这是一个安全的演员。您已创建Derived实例 这就是为什么将 Derived as 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.");
  }

答案 2 :(得分:0)

不,它不会丢失信息。但是,如果首先从未出现该信息,则演员表可能会失败。如果b从不是Derived类型或派生类型,它将抛出异常。

Base b = new b();
// Some actions
Derived d = (Derived)b; // will fail, b never was of type Derived.

答案 3 :(得分:0)

1)当“GC将擦除......存储b的内存块”时,你的代码“=(Derived)b”b不再在内存中,当然它会失败,但GC不应该除非你玩弱引用,否则不要擦除它。

2)Base b = new Derived(); 我不明白你为什么要做这个“向上倾斜”。 您的代码已经具有强大的参考/类型Derived,也可以使用Derived b = ....