属性(System.Attribute)を作成して、属性を付けたクラスとメソッドを列挙する。

サンプルコード:LoadAssembley-2.zip 直

Visual Studio 2008 でXMLコメントを打つと以下のように出力されます。


'''
'''
'''

'''
Public Shared Sub Main()

Summary(要約)やRemarks(注釈)は記載できますが、プログラムを書いた人(Author)の情報を入力する欄がないのでXMLコメントの代わりに属性でAuthor情報を設定できるようにAuthor属性を作成してみます。また、Author情報を付与したクラス名・メンバ名を抽出して列挙するプログラムを書いてみます。

Author属性クラス


_
Public Class AuthorAttribute
Inherits System.Attribute

Public Name As String = String.Empty

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

End Class

属性を作成するためには、System.Attributeを継承してクラスを作成します。クラス名は属性名+Attributeで設定します。属性に渡す引数(Authorの場合はプログラムを書いた人の名前)は、コンストラクタを通じて渡します。名前の他に、コメントや作成日を追加で渡す場合は、コンストラクタの引数を増やします。

属性クラスにはAttributeUssage属性を付けて属性の使用方法を設定することが出来ます。クラスだけに付ける、メソッドだけに付ける、プロパティだけに付けるなど属性を付ける箇所(AttributeTargets)、属性を複数(2個以上)付けることが出来るかどうか(AllowMultiple)、継承後のクラスにも属性を適用するかどうか(Inherited)などがあります。今回は、クラスでもメソッドでもプロパティでも何でも付けれて、複数の名前を付けることができ、継承後の派生先クラスには属性を適用しないという設定にします。

次に属性を以下のように任意の箇所に付与してみます。

Author属性の設定例


Imports LoadAssembley

_
Public Class Form1

_
Public Shared Sub Main()

End Sub

_
Public Sub Main2()

End Sub

_
Public Property Prop1()
Get
Return 0
End Get
Set(ByVal value)

End Set
End Property

End Class

これで、Author情報を付けることができる下地ができました。付けただけではメモ程度にしかならないので(それならコメントで問題ないという話)なので、リフレクションを使用して属性を抽出して、レポートにするなどの処理を考えて見ます。

以下は、アセンブリから、クラス情報を列挙しクラスのカスタム属性とクラスメンバのカスタム属性を抽出するサンプルです。


Public Class StartUp

'''


'''
'''

'''
Public Shared Sub Main()

Dim asm As System.Reflection.Assembly = Nothing

Try
asm = System.Reflection.Assembly.LoadFrom("Author.dll")
Catch ex As System.IO.FileNotFoundException
Debug.Print("NOT FOUND")
End Try

If Not asm Is Nothing Then

For Each item As System.Type In asm.GetTypes()

For Each itemAttributeObject As Object In item.GetCustomAttributes(False)

If TypeOf (itemAttributeObject) Is AuthorAttribute Then

Dim itemAttribute As AuthorAttribute = CType(itemAttributeObject, AuthorAttribute)
Debug.Print(item.FullName + " " + "Author:" + itemAttribute.Name)

End If

Next

For Each mi As System.Reflection.MemberInfo In item.GetMembers

For Each itemAttributeObject As Object In mi.GetCustomAttributes(False)

If TypeOf (itemAttributeObject) Is AuthorAttribute Then

Dim itemAttribute As AuthorAttribute = CType(itemAttributeObject, AuthorAttribute)
Debug.Print(item.FullName + "." + mi.Name + " " + "Author:" + itemAttribute.Name)

End If

Next

Next

Next

End If

End Sub

End Class

上記の処理を実行するとイミディエイトウインドウに以下のように表示されます。

Author.Form1 Author:tekk
Author.Form1.Main Author:tekk-1
Author.Form1.Main2 Author:tekk-1
Author.Form1.Prop1 Author:tekk-2