日々迷走

yan note

ホーム 連絡をする 同期する ( RSS 2.0 ) Login
投稿数  9  : 記事  0  : コメント  207  : トラックバック  3

書庫

日記カテゴリ

前回に引き続き定数定義クラスについてです。

今回はT.Hiraseさんからパクッた教えていただいたカスタム属性を使って名前付定数を定義してみました。
T.hiraseさんの記事:[C#] 名前付き定数・・・?
ありがとうございます(人-)謝謝

前回に比べ、
定数を定義する際はConstantクラスに列挙体を追加するだけなので楽になりました。
しかし定数を使用する際が直感的に解りにくくなってしまいました。
DayOfWeek.CreateListで定数リストデータが作成できたり DayOfWeek.GetName(DayOfWeekの列挙子)で定数の名前を取れるようにしたいですね。

定数を定義する際は列挙体を使用してカスタム属性で定数名を定義します。
Public Class Constant
  Public Enum DayOfWeek As Integer
        <("日曜日"), AliasName("日")> _
        Sun = 0
        <("月曜日"), AliasName("月")> _
        Mon = 1
        <("火曜日"), AliasName("火")> _
        Tue = 2
        <("水曜日"), AliasName("水")> _
        Wed = 3
        <("木曜日"), AliasName("木")> _
        Thu = 4
        <("金曜日"), AliasName("金")> _
        Fri = 5
        <("土曜日"), AliasName("土")> _
        Sat = 6
    End Enum
    
    Public Shared Function CreateList(ByVal enumType As Type) As List(Of ListItem)
        Dim items As New List(Of ListItem)
        For Each value As Object In [Enum].GetValues(enumType)
            Dim name As String = NameAttribute.GetName(CType(value, [Enum]))
            items.Add(New ListItem(value, name))
        Next
        Return items
    End Function

    Public Shared Function CreateAliasList(ByVal enumType As Type) As List(Of ListItem)
        Dim items As New List(Of ListItem)
        For Each value As Object In [Enum].GetValues(enumType)
            Dim aliasName As String = AliasNameAttribute.GetAliasName(CType(value, [Enum]))
            items.Add(New ListItem(value, aliasName))
        Next
        Return items
    End Function

    Public Shared Function GetName(ByVal enumType As Type, ByVal findValue As Object) As String
        Return NameAttribute.GetName(CType(findValue, [Enum]))
    End Function

    Public Shared Function GetAliasName(ByVal enumType As Type, ByVal findValue As Object) As String
        Return AliasNameAttribute.GetAliasName(CType(findValue, [Enum]))
    End Function
    
End Class


Imports System.Reflection
<AttributeUsage(AttributeTargets.All)> _
Friend Class NameAttribute
    Inherits Attribute

    Private _name As String

    Public Property Name() As String
        Get
            Return Me._name
        End Get
        Private Set(ByVal value As String)
            Me._name = value
        End Set
    End Property

    Public Sub New(ByVal name As String)
        Me.Name = name
    End Sub

    Public Shared Function GetName(ByVal enumValue As [Enum]) As String
        Dim enumType As Type = enumValue.[GetType]()
        Dim enumName As String = [Enum].GetName(enumType, enumValue)
        If enumName Is Nothing Then
            Return Nothing
        Else
            Return GetName(enumType.GetField(enumName))
        End If
    End Function

    Private Shared Function GetName(ByVal type As MemberInfo) As String
        Dim attributes As Attribute()
        attributes = TryCast(type.GetCustomAttributes(GetType(NameAttribute), True), Attribute())
        If attributes Is Nothing OrElse attributes.Length = 0 Then
            Return Nothing
        End If
        Dim nameAttribute As NameAttribute = TryCast(attributes(0), NameAttribute)
        Return nameAttribute.Name
    End Function

End Class


Imports System.Reflection
<AttributeUsage(AttributeTargets.All)> _
Friend Class AliasNameAttribute
    Inherits Attribute

    Private _aliasName As String

    Public Property AliasName() As String
        Get
            Return Me._aliasName
        End Get
        Private Set(ByVal value As String)
            Me._aliasName = value
        End Set
    End Property

    Public Sub New(ByVal aliasName As String)
        Me.AliasName = aliasName
    End Sub

    Public Shared Function GetAliasName(ByVal enumValue As [Enum]) As String
        Dim enumType As Type = enumValue.GetType
        Dim enumName As String = [Enum].GetName(enumType, enumValue)
        If enumName Is Nothing Then
            Return Nothing
        Else
            Return GetAliasName(enumType.GetField(enumName))
        End If
    End Function

    Private Shared Function GetAliasName(ByVal type As MemberInfo) As String
        Dim attributes As Attribute()
        attributes = TryCast(type.GetCustomAttributes(GetType(AliasNameAttribute), True), Attribute())
        If attributes Is Nothing OrElse attributes.Length = 0 Then
            Return Nothing
        End If
        Dim nameAttribute As AliasNameAttribute = TryCast(attributes(0), AliasNameAttribute)
        Return nameAttribute.AliasName
    End Function

End Class


使うときはConstantクラスのCreateListメソッドのパラメータに列挙体のTypeを指定します。
With Me.cboDayOfWeekLong
    .ValueMember = "Key"
    .DisplayMember = "Value"
    .BeginUpdate()
    .DataSource = Constant.CreateList(GetType(Constant.DayOfWeek))
    .EndUpdate()
    .SelectedValue = Constant.DayOfWeek.Sat
End With

With Me.cboDayOfWeekShort
    .ValueMember = "Key"
    .DisplayMember = "Value"
    .BeginUpdate()
    .DataSource = Constant.CreateAliasList(GetType(Constant.DayOfWeek))
    .EndUpdate()
    .SelectedValue = CType(4, Constant.DayOfWeek)
End With
        
Dim findValue As Constant.DayOfWeek = CType(2, Constant.DayOfWeek)
Dim name As String = Constant.GetName(GetType(Constant.DayOfWeek), findValue)
Dim aliasName As String = Constant.GetAliasName(GetType(Constant.DayOfWeek), findValue)
投稿日時 : 2008年3月30日 14:27

コメント

# re: 定数定義クラス その2 2008/03/30 17:05 黒龍
Enumとリフレクションは処理量が多いので定数のよさをスポイルするような気がしないでもないです。
IEnumerable<KeyValuePair<TKey, TValue>>なコレクションでyield Return並べるとかは駄目かな?


# re: 定数定義クラス その2 2008/03/30 20:54 yan
・・・VBにyield Returnはない( ´・ω・)ショボーン

# KefLOECWrdsGXSMWVKR 2011/09/29 3:38 http://oemfinder.com
EvbyyE Uh, well, explain me a please, I am not quite in the subject, how can it be?!...

# IKKzkEiIrontiljtnE 2011/11/02 5:12 http://www.pharmaciecambier.com/
Stupid article..!

# qlUTBRfZpoQkxm 2011/11/02 6:05 http://optclinic.com/
Totally agree with you, about a week ago wrote about the same in my blog..!

# ZYhuakOvxXkXOXPPt 2011/11/16 3:19 http://www.hansensurf.com/Backpacks-And-Luggage.ht
Hello! How do you feel about young composers?!...

# yezi20160620@163.com 2017/09/28 9:58 wwwww
http://www.shoesjordan.us.com
http://www.lacosteonlineshop.us.com
http://www.hermes-belt.co.uk
http://www.michaelkors-outletonlines.us.com
http://www.longchamphandbagsoutlet.us.org
http://www.truereligionjeans-outlets.us.com
http://www.longchamphandbags.us.org
http://www.nikehuaracheshoes.us.com
http://www.converseoutlet.us.com
http://www.jordan11retro.us.com
http://www.adidasstansmith.us.com
http://www.cheap--jordans.us.com
http://www.authenticjordanscheap.us.com
http://www.jordan-retro.us.com
http://www.thelightupshoes.us.com
http://www.yeezy-boost.us.com
http://www.yeezy-shoes.us
http://www.retro-jordans.us.com
http://www.nikedunks.us.org
http://www.nikebasketballshoes.us.com
WWW

# Air Max 270 2019/04/13 8:21 qqrnocxwql@hotmaill.com
qitpdz,Definitely believe that which you said. Your favourite justification appeared to be on the net the simplest thing to remember of.

# Jordan 12 Gym Red 2018 2019/04/27 3:38 ccwwyvstzuh@hotmaill.com
Apple had expected it to reach this milestone more than six months ago, but in order to maintain its leading position, Spotify has expanded its various promotions, including the launch of a discount subscription package with video streaming service Hulu. Recently,

# Nike Element 87 2019/05/03 0:14 jzxemhwlt@hotmaill.com
A lady said she'd take my daughter, he recalled. "I carried my son downstairs to an ambulance, we took him to the hospital. I yelled, Please help my son! Please help! Please help!

# Pandora Rings Official Site 2019/06/08 15:01 beqwgselew@hotmaill.com
http://www.dallascowboysjerseyscheap.us/ Dallas Cowboys Jerseys

# Travis Scott Jordan 1 2019/06/14 1:01 efgrtm@hotmaill.com
jfyhjhmqv Yeezy Boost 350,Very helpful and best artical information Thanks For sharing.

# Cheap NFL Jerseys 2019/07/01 18:15 wqgfjlwewdl@hotmaill.com
http://www.yeezy500utilityblack.com/ Yeezy 500

# aKbfoVSnJUIRjvV 2022/04/19 11:58 johnansaz
http://imrdsoacha.gov.co/silvitra-120mg-qrms

# scary swallow roller golf preacher some flows 2022/06/02 17:51 piendamp
menace romans blend commands script hee
https://www.dsb.cn/check?link=https%3A%2F%2Fstromectol4pro.top
dealer defend neal oxygen ended shovel catherine practically

# fast ed meds online - https://cheapdr.top/# 2023/04/03 15:39 Dikolipo
fast ed meds online - https://cheapdr.top/#

# doxycycline 500mg - https://doxycyclinesale.pro/# 2023/04/22 4:15 Doxycycline
doxycycline 500mg - https://doxycyclinesale.pro/#

# paxlovid for sale https://paxlovid.pro/# - paxlovid 2023/07/03 4:12 Paxlovid
paxlovid for sale https://paxlovid.pro/# - paxlovid

# paxlovid india https://paxlovid.life/# paxlovid buy 2023/07/26 6:29 Paxlovid
paxlovid india https://paxlovid.life/# paxlovid buy

# best over the counter ed pills https://edpills.ink/# - best ed drug 2023/07/27 1:02 EdPills
best over the counter ed pills https://edpills.ink/# - best ed drug

# buy cytotec over the counter https://cytotec.ink/# - Abortion pills online 2023/07/27 1:26 PillsFree
buy cytotec over the counter https://cytotec.ink/# - Abortion pills online

# cheapest ed pills https://edpillsotc.store/# - top erection pills 2023/10/08 1:21 EdPills
cheapest ed pills https://edpillsotc.store/# - top erection pills

# doxycycline hyc 100mg https://doxycycline.forum/ doxycycline 2023/11/25 13:22 Doxycycline
doxycycline hyc 100mg https://doxycycline.forum/ doxycycline

# ed pills otc https://edpills.tech/# generic ed pills 2023/12/23 8:19 EdPills
ed pills otc https://edpills.tech/# generic ed pills

# buying prednisone from canada https://prednisonepharm.store/ can you buy prednisone over the counter in usa 2024/01/20 17:37 Prednisone
buying prednisone from canada https://prednisonepharm.store/ can you buy prednisone over the counter in usa

# natural ed remedies https://edpill.cheap/ best ed treatment 2024/02/09 19:56 EdPills
natural ed remedies https://edpill.cheap/ best ed treatment

# lana rhoades izle - https://lanarhoades.fun/ lana rhoades video
2024/03/03 1:42 LanaRho
lana rhoades izle - https://lanarhoades.fun/ lana rhoades video


# eva elfie https://evaelfie.pro/ eva elfie 2024/03/03 10:28 EvaElfia
eva elfie https://evaelfie.pro/ eva elfie

# abella danger izle https://abelladanger.online/ abella danger izle
2024/03/06 11:00 Adella
abella danger izle https://abelladanger.online/ abella danger izle


# lana rhoades boyfriend - https://lanarhoades.pro/ lana rhoades unleashed
2024/03/06 13:37 LanaRho
lana rhoades boyfriend - https://lanarhoades.pro/ lana rhoades unleashed


# eva elfie hd https://evaelfie.site/ eva elfie
2024/03/07 1:58 EvaElfie
eva elfie hd https://evaelfie.site/ eva elfie


# sweet bonanza free spin demo https://sweetbonanza.bid/ - sweet bonanza kazanma saatleri
2024/03/27 19:25 Bonanzaj
sweet bonanza free spin demo https://sweetbonanza.bid/ - sweet bonanza kazanma saatleri


# gates of olympus oyna - https://gatesofolympus.auction/ gates of olympus 1000 demo 2024/03/27 20:45 Olympic
gates of olympus oyna - https://gatesofolympus.auction/ gates of olympus 1000 demo

# Clava is the best 2025/05/09 14:19 Danielthash
Greatest news for all us

# re: 定数定義クラス その2 2025/09/16 18:36 CharlescCheng
IP地址??工具,?跨境?商?家提供快速准?,支持全球范?内的IP地址??,可以?助跨境?商?家通???IP地址,?松跨越国界?看其位置,地??示更直?。

# re: 定数定義クラス その2 2025/09/16 18:37 CharlescCheng
IP地址??工具,?跨境?商?家提供快速准?,支持全球范?内的IP地址??,可以?助跨境?商?家通???IP地址,?松跨越国界?看其位置,地??示更直?。

# re: 定数定義クラス その2 2025/09/16 18:37 CharlescCheng
IP地址??工具,?跨境?商?家提供快速准?,支持全球范?内的IP地址??,可以?助跨境?商?家通???IP地址,?松跨越国界?看其位置,地??示更直?。

# re: 定数定義クラス その2 2025/09/16 18:38 CharlescCheng
IP地址??工具,?跨境?商?家提供快速准?,支持全球范?内的IP地址??,可以?助跨境?商?家通???IP地址,?松跨越国界?看其位置,地??示更直?。

# re: 定数定義クラス その2 2025/09/16 18:42 CharlescCheng
The IP address query tool provides cross-border e-commerce sellers with fast and accurate services, supporting global IP address queries. It enables cross-border e-commerce sellers to easily view their locations across borders by querying IP addresses, and the map display is more intuitive.:https://www.amz123.com/tools-ip

Post Feedback

タイトル
名前
Url:
コメント