雑記 - otherwise

最近はDQ10しかやっていないダメ技術者がちまちまと綴る雑記帳

プロパティに設定された属性値を取得する

TwitterR.田中一郎さんがつぶやいていたのを見て、あまり確認せずに「 Attribute.GetCustomAttributes() で出来るのでは」と返してみたのですが、ちょっと気になったので手元でもやってみました。
ちょっと手間取ったので、備忘録もかねて記事にしておきます。

// カスタム属性
public class AuthorAttribute : Attribute {
  public string Name { get; set; }

  public AuthorAttribute(string name) {
    this.Name = name;
  }
}

// 対象クラス
public class Foo {
  // プロパティに属性を付ける
  [Author("有馬菜々")]
  public string Bar { get; set; }
}

// テスト
public class test {
  static void Main() {
    // プロパティに付いている属性を取得する
    var authors =
            Attribute.GetCustomAttributes(
                typeof(Foo).GetProperty("Bar"),
                typeof(AuthorAttribute)) as AuthorAttribute[];
    // 取得内容の確認
    if (authors != null) {
      foreach (var author in authors) {
        Console.WriteLine(author.Name);
      }
    }
  }
}

一応これで取れるみたいです。間違ってなくてよかった。 ^^;