1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【VB.Net】「区分オブジェクト」のようなクラスを作れないか試行錯誤

Last updated at Posted at 2021-04-30

※ 個人blogに投稿した記事(投稿日:2019/10/10)をQiitaに移行しました

前回の「区分オブジェクト」に関する投稿に引き続いて関連した投稿を。
列挙型の区分ごとにプロパティを持たせる事ができないかなと思い、
実装してみたのが以下のような抽象クラスと具象クラスを使う形式。

Public MustInherit Class Perfume

    Public ReadOnly Property myFavorite As Boolean
    Sub New(myFavorite As Boolean)
        Me.myFavorite = myFavorite
    End Sub

    Public Class Nocchi
        Inherits Perfume

        Sub New(myFavorite As Boolean)
            MyBase.New(myFavorite)
        End Sub

    End Class

    Public Class Kashiyuka
        Inherits Perfume

        Sub New(myFavorite As Boolean)
            MyBase.New(myFavorite)
        End Sub

    End Class

    Public Class AaChan
        Inherits Perfume

        Sub New(myFavorite As Boolean)
            MyBase.New(myFavorite)
        End Sub

    End Class

End Class

クラス名からインスタンスを生成するにはActivator.CreateInstance
区分の判定はGetTypeで列挙型と同様に行えます。

Module Module1

    Sub Main()

        Dim myPerfume = createMyFavoriteMember("Nocchi")

        Select Case myPerfume.GetType()
            Case GetType(Perfume.Nocchi)
                ' ...
            Case GetType(Perfume.Kashiyuka)
                ' ...
            Case GetType(Perfume.AaChan)
                ' ...
        End Select
    End Sub

    Private Function createMyFavoriteMember(memberName As String) As Perfume
        Return CType(Activator.CreateInstance(
                                    Type.GetType("Enumeration.Perfume+" & memberName),
                                    New Object() {True}), Perfume)
    End Function
End Module

実行すると以下のようになります。

20191010231631.png

うーん・・・具象クラスのコンストラクタを全部書く必要があるのと、
Activator.CreateInstanceでType名をセットする部分があまりイケてない感じがする・・・

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?