Ognacの雑感

木漏れ日々

目次

Blog 利用状況

書庫

ギャラリ

動的に配列操作する

アプリで操作する配列の要素数の変更はRedimで可能です。
アプリによっては,実行時に次元数を任意に設定したいことがあります。下記のMethodを書きました。

    Friend Function makeArray(of T)(str as String)
        Dim fact As String() = str.Split(","c)
        Dim aryLen(fact.Length - 1) As Integer
        For i As Integer = 0 To fact.Length - 1
            If IsNumeric(fact(i)) Then aryLen(i) = CInt(fact(i))
        Next
        ary = Array.CreateInstance(GetType(T), aryLen)
        return ary
    End Function


ジェネリックが可能になったおかげで、動的に任意の型と任意の次元/要素の配列を作成できます。

 値の設定/取得も動的に出来ないと意味が半減するので書いてみました。


    Friend Sub 設定(Of T)(ByVal str As String, ByVal 値 As T)
        Dim S_fact As String() = str.Split(","c)
        Dim l_fact(S_fact.Length - 1) As Long
        For i As Integer = 0 To S_fact.Length - 1
            Dim o As String = S_fact(i)
            l_fact(i) = CLng(o)
        Next
        ar.SetValue(値, l_fact)
    End Sub

    Friend Function 取得(Of T)(ByVal str As String) As T
        Dim S_fact As String() = str.Split(","c)
        Dim l_fact(S_fact.Length - 1) As Long
        For i As Integer = 0 To S_fact.Length - 1
            Dim o As String = S_fact(i)
            l_fact(i) = CLng(o)
        Next
        Return DirectCast(ar.GetValue(l_fact), T)
    End Function

使用例:
 dim ar as array = makeArray(of Long)("3,5,6,7")
 設定(of Long)("3,4,5,6",456786)

 dim v as long = 取得(of Long)("4,3,2,2")

 のように使えます。  便利に書けるもんだ。ジェネリック様々ですね。
 一つ残念なのは 文字配列を数字配列にCopy出来ない点ですね。
  文字配列.copy(数字配列,0)  などが可能ならもってスッキリできると思います。

と周りに話したら、ソースの可読性が低いから個別に明示的に書いてくれと言われた。可読性はないのかな?


 

投稿日時 : 2007年1月28日 15:02

Feedback

No comments posted yet.
タイトル
名前
Url
コメント