型情報以外のメタデータとして属性も挙げられます。 .NETでは属性を使うことでプログラムに型情報以外の追加的なメタデータを埋め込むことができ、それを実行時に取得・参照することができます。 属性にはコンパイラやランタイムが特別な操作を行うために使用されるものが存在するほか、独自に意味を定義して情報を埋め込むカスタム属性があります。
カスタム属性でメタデータを埋め込み、リフレクションにより埋め込んだメタデータを実行時に取得する
using System;
using System.Reflection;
// カスタム属性となるクラス
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class AuthorAttribute : Attribute {
public string Name {
get; private set;
}
public string Version;
public AuthorAttribute(string name)
{
this.Name = name;
}
}
class Sample {
// カスタム属性が設定されたメソッド
[Author("Alice", Version = "1.0")]
[Author("Bob", Version = "1.1")]
[Author("Charlie", Version = "1.2")]
public static void TestMethod()
{
}
static void Main()
{
// メソッドの情報を取得する
var method = typeof(Sample).GetMethod("TestMethod");
// メソッドに設定されているカスタム属性を取得して列挙する
foreach (AuthorAttribute attr in method.GetCustomAttributes(typeof(AuthorAttribute), false)) {
// 属性に設定されている値を表示する
Console.WriteLine("Author: {0}, Version: {1}", attr.Name, attr.Version);
}
}
}
実行結果例
Author: Charlie, Version: 1.2 Author: Bob, Version: 1.1 Author: Alice, Version: 1.0
代表的な属性として、プログラムのバージョン情報を埋め込むための属性(アセンブリのバージョン情報を設定・取得する)や、旧式化されたAPIであることを示すObsolete属性(機能の廃止・非推奨化)、オブジェクトをシリアライズする際の動作を定義する属性(シリアライズの基本)などがあります。
その他、属性について、および属性の使用方法や独自に定義してその情報を取得する方法などについて詳しくは属性とメタデータで個別に解説しています。