LoginSignup
11
12

More than 5 years have passed since last update.

【C#】カスタムAttributeまとめ 概要編

Last updated at Posted at 2018-07-23

概要

自作でAttributeをするときのメモとしてまとめようと思います。

カスタムAttribute

カスタムAttributeはAttributeクラスをアトリビュートを付けたい対象のクラスに継承することで実現します。

例としでint型の値を入れられるAttributeを作ってみます。
何をしているかの説明は次の項目で説明します。


[System.AttributeUsage(AttributeTargets.All,
 Inherited = false, AllowMultiple = true)]
sealed class TestIntAttribute : Attribute
{
    public TestIntAttribute(int value)
    {
        this.value = value;
    }

    public int value { get; set; }
}

参考
AttributeUsage (C#)
https://docs.microsoft.com/ja-jp/dotnet/csharp/programming-guide/concepts/attributes/attributeusage

AttributeTargets

Attributeは付けられる対象を指定できます。
クラスだけに付けたいとか、フィールドとプロパティだけに付けたいとかそんな感じです。全ての対象につけることも出来ます。

付けられる設定は以下です。

AttributeTargets 内容
All 全ての要素で使える
Assembly アセンブリに使える
Class クラスで使える
Constructor コンストラクタで使える
Delegate デリゲートで使える
Enum 列挙型で使える
Event イベントで使える
Field フィールドで使える
GenericParameter ジェネリックパラメータで使える
Interface インターフェースで使える
Method メソッドで使える
Module モジュールで使える
Parameter パラメーターで使える
Property プロパティで使える
ReturnValue 戻り値で使える
Struct 構造体で使える

AllowMultiple

複数のAttributeを付けられるかのプロパティです。
デフォルトはfalseになってます。

Inherited

カスタムAttributeを付けたクラスの継承先でも使えるかどうかを示すプロパティです。
デフォルトはfalseになってます。

終わりに

なんとなくですが自分なりにまとめました。
実際に作ったカスタムAttributeの取得は次回以降にやります。

11
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
12