2

If, in code, I wanted to do something like the following, what would my class definition need to look like? (Keep in mind the fruit/language thing is just an example)

dim myfruit as new fruit()
myfruit.name = "apple"
myfruit.name.spanish = "manzana"

Here is the class I have, just not sure how to add the "sub property".

Public Class Fruit
    Private _name As String
    Public Property name() As String
        Get
            Return _name 
        End Get
        Set(ByVal value As String)
            _name = value
        End Set
    End Property
End Class
4

2 回答 2

4

一般来说,要让您拥有“子属性”,您需要将您的属性本身设为一个类。这意味着子属性实际上是由顶级属性公开的类的属性。

实际上,您可以将 name 属性从字符串更改为“翻译”类或类似的,即:

Public Class Fruit
    Public Property Name As New Translations
End Class

Public Class Translations
    Public Property Primary As String
    public Property Spanish As String
End Class

但是,这可能会破坏您显示的代码,因为第二行需要具有不同的语法,即:

myfruit.Name.Primary = "green"
myfruit.Name.Spanish = "verde"

但是,如果这里的目标只是处理用户界面的翻译,还有其他选择。有关详细信息,请参阅MSDN上的基于 .NET Framework 的国际应用程序介绍

于 2013-09-16T19:06:12.717 回答
0

我最初认为里德的答案是我所追求的。在我的应用程序中,我想使用“子属性”在表单标签上设置属性。(我试图只发出我希望自定义控件可用的标签属性。)

我试过这个:

Public Class Fruit
    Private _name As New Translations
    Public Property Name As Translations
        Get
            Return _name
        End Get
        Set(value As Translations)
            _name = value
            _PrimaryCaps = _name.Primary.ToUpper
        End Set
    End Property
    'Private variable is automatically added for unexpanded property
    Public Property PrimaryCaps As String
End Class

Public Class Translations
    Public Property Primary As String
    Public Property Spanish As String
End Class

然后

Dim myFruit As New Fruit
myFruit.Name.Primary = "Apple"
myFruit.Name.Spanish = "Manzana"
Dim primaryCaps As String = myFruit.PrimaryCaps

奇怪的是——至少对我来说——这行不通;myFruit.PrimaryCaps 只返回希望的“APPLE”。似乎从未执行 Set for Name。(但是,将 _PrimaryCaps 赋值放在 Get Return 上方确实有效。)

(我意识到可以将 PrimaryCaps 属性添加到 Translations 类,但是,如果您想从 Fruit 的实例中设置外部变量,这也无济于事。)

我不知道这是否是“设计使然”,是我只是误解了预期的功能还是什么。在进一步研究后我发现的一件事是这种结构在 .NET 中根本不常见。例如设置控件的大小如下:

oControl.Size = New Drawing.Size(20, 15)

而不是简单地直接设置 Width 属性:

oControl.Size.Width = 20

(后者不会编译:“表达式是一个值,因此不能成为赋值的目标。”)

如果有人对此有比我更多的见解,我很想听听。例如,我知道这可以简单地通过使用 Fruit 的实例来完成,但这不是重点。

于 2016-12-20T04:50:19.453 回答