2012-03-30 36 views
1

我有结构化这样的类:性质调节

Public MustInherit Class A 
    ' several properties 
End Class 

Public Class B 
    Inherits A 
    ' several properties 
End Class 

Public MustInherit Class C 
    Protected _X As A 
    Public ReadOnly Property X As A 
    Get 
     Return _X 
    End Get 
    End Property 
End Class 

Public Class D 
    Inherits C 
    Private _X As B 
    Public ReadOnly Property X As B 
    Get 
     Return _X 
    End Get 
    End Property 
    Sub New 
    _X = New B 
    End Sub 
End Class 

是否有修改,我可以在d类属性X使用,这将导致X从得自d的实例和返回为B评估为C的D的实例?

Dim d As New D 
Response.Write((d.X Is Nothing) & "<br>") 
Dim c As C = d 
Response.Write(c.X Is Nothing) 

在这两种情况下,我要X到不能为Nothing

我知道我可以修改d如下:

Public Class D 
    Inherits C 
    Private __X As B 
    Public ReadOnly Property X As B 
    Get 
     Return __X 
    End Get 
    End Property 
    Sub New 
    __X = New B 
    _X = __X 
    End Sub 
End Class 

是否有一个清晰的解决方案?

+0

我还没有尝试过我自己,但我相信,如果你确实编译这段代码,你会被告知到指定'Shadows'或者你需要改变'C'的'X'为'可覆盖'。我没有检查,但我_think_“阴影”会做你想做的。 – 2012-03-30 01:18:43

+0

你对编译器是正确的 - 它说使用'Overloads',但它也很满意'Shadows'。不幸的是,没有人解决这个问题。 – ic3b3rg 2012-03-30 01:37:59

回答

0

你应该使用Shadows避免新的代码,但如果你真的需要这个结构,我明白你只用添加MyBase._X=_XD的预期结果New选项1),它也可以做通过D调用C中的New,然后进行相反的赋值_X = DirectCast(MyBase._X, B)选项2)。

当然另一种选择,这取决于你的实际意图,是砸在Private _X As BD投只是在_XB在你的阴影X。 (选项3

这是我的代码与选项1和2注释和当前执行选项3

Public MustInherit Class C 
    Protected _X As A 
    ''Option 2: 
    'Protected Sub New(X As A) 
    ' _X = X 
    'End Sub 
    Public Overridable ReadOnly Property X As A 
     Get 
      Return _X 
     End Get 
    End Property 
End Class 

Public Class D 
    Inherits C 
    'Commented out for option 3: 
    'Private Shadows _X As B 
    Public Shadows ReadOnly Property X As B 
     Get 
      'Commented out for option 3: 
      'Return _X 
      Return DirectCast(_X, B) 
     End Get 
    End Property 
    Sub New() 
     ''Option 1,3: (Comment out for option 2) 
     _X = New B 
     ''Option 1: 
     'MyBase._X = _X 
     ''Option 2: 
     'MyBase.New(New B) 
     '_X = DirectCast(MyBase._X, B) 
    End Sub 
End Class 
+0

我没有测试所有的选项,但我认为只有选项2将工作。基本上,如果我将B存储为A,然后将其重新写入B,那么在这个过程中我将失去任何B属性。选项2比我想出的更清洁 - 谢谢! – ic3b3rg 2012-03-30 05:52:40

+0

@ ic3b3rg你说:“如果我将'B'存储为'A',然后将其重写为'B',那么在这个过程中我将失去任何'B'属性:”这只是一个强制转换,对象是仍然是一个'B';其属性仍然存在。它只是Shadows的一个特性(当有可用时可以用Overrides),以及你主要问题的要求是什么,它允许你通过'A'类到'B'对象的变化。 – 2012-03-30 06:07:18