C#のAttributeの概要

9858 ワード

最近使ったので、落ち着いて資料を探してみて、やっとこれを明らかにしました.
一.Attributeとは
まず、次の3つのコードを見てください.
1.カスタムAttributeクラス:VersionAttribute
    [AttributeUsage(AttributeTargets.Class)]
    public class VersionAttribute : Attribute
    {
        public string Name { get; set; }
        public string Date { get; set; }
        public string Describtion { get; set; }
    }

2.カスタムAttributeのClassを使用するには:
    [Version(Name = "hyddd", Date = "2009-07-20", Describtion = "hyddd's class")]
    public class MyCode
    {
        //...
    }

<!--
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
--> 3.上のクラスのAttributeは一般的にどのように使われていますか?
    class Program
    {
        static void Main(string[] args)
        {
            var info = typeof(MyCode);
            var classAttribute = (VersionAttribute)Attribute.GetCustomAttribute(info, typeof(VersionAttribute));
            Console.WriteLine(classAttribute.Name);
            Console.WriteLine(classAttribute.Date);
            Console.WriteLine(classAttribute.Describtion);
        }
    }

例完了!上の3つのコードは、Attributeが何なのか、どのように使われているのかを説明していると信じています.
二.Attributeの詳細
1.Attributeの概念定義
Attributeの概念の定義については、「知っておくべき.NETの特性と属性」の一節を直接引用して説明します.
MADNの定義は、共通言語の実行時に、タイプ、フィールド、メソッド、プロパティなどのプログラム内の要素に寸法を付けるattributesというキーワードのような記述宣言を追加できるようにすることです.AttributesとMicrosoftNET Frameworkファイルのメタデータ(metadata)は、実行時にコードを記述したり、プログラムの実行時にアプリケーションの動作に影響を与えるために保存されます.
単純にまとめると、カスタムプロパティattributeは、本質的にターゲット要素に関連する追加情報を提供し、実行中に反射的に追加情報を取得するクラスです.
ああ、Attributeの目的は要素に関連する追加情報を提供することでした.ここで、上記第1セグメントコードの「[AttributeUsage(AttributeTargets.Class)」は、Attributeが追加情報を提供する要素がClassであることを示しているので、上記第2セグメントのコードを次のように変更すると、
public class MyCode
{
    [Version(Name = "hyddd", Date = "2009-07-20", Describtion = "hyddd's class")]
 public void Test() { }
}

<!--
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
-->
コンパイルエラーが発生します.
2.コンパイル命令としてAttribute
Attributeクラスは、通常のクラスのように実行時にインスタンス化されるのではなく、コンパイル時にインスタンス化されます.したがって、第3セグメントのコードでは、MyCodeオブジェクトをインスタンス化せずにMyCodeのAttribute情報を取得できます.Attributeクラスはコンパイル時にインスタンス化されるため、外部ツールでこれらのAttribute情報を維持することもできます.
3.AttributeとProperty
中国語から言えば、AttributeとPropertyの中国語は「属性」と呼ばれ、混同されやすい.現在の記事では、Attributeは一般的に「プロパティ」と訳され、Propertyは「プロパティ」と呼ばれています.
もしかすると、私は静的なProperty/Fieldのようにインスタンス化しないうちにいくつかの情報を得ることができます.もしそうなら、Attributeには何の意味がありますか?
1.Property:
Propertyはオブジェクト向けの概念と言え、プライベートフィールドへのアクセスパッケージを提供し、C#でgetとsetアクセスメソッドで読み取り可能書き込み可能な属性の操作を実現し、安全で柔軟なデータアクセスパッケージを提供しています.例:
    public class Robot
    {
        private string name = "";   // :Field
        public string Name          // :Property, Field 。
          {
            get { return name; }
            set { name = value; }
        }
    }

<!--
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
--> 2.Attribute:
Attributeの目的は、要素に追加情報を提供することです.その役割はコメントに似ています.
Property/FieldとAttributeは2つの全く異なる概念であり、彼らは時々同じことをすることができるが、彼らは本質的に異なる2つのものであることを覚えておいてください.
三.自分のAttributeを実現する上で注意しなければならない問題
1.カスタムAttributeは、直接または間接的にSystemを継承する必要がある.Attribute.
2.ここには、すべてのカスタムプロパティ名にAttribute接尾辞が必要です.プログラムの要素にAttributeが適用されると、コンパイラはまずAttributeの定義を検索し、見つからない場合は、すると、「Attribute名」+Attributeの定義が検索されます.見つからない場合は、コンパイラがエラーを報告します.これは、上の最初のセグメントコードでVersionAttributeを定義できる理由ですが、2番目のセグメントコードではVersionというAttributeを使用しています.:>
以下に、カスタムAttributeを開発する際に使用する資料を示します.
Attributeに関連付けられる要素は次のとおりです.
プログラムセット(assembly)、モジュール(module)、タイプ(type)、プロパティ(property)、イベント(event)、フィールド(field)、メソッド(method)、パラメータ(param)、戻り値(return).例:
    [assembly: Version(Name = "hyddd", Date = "2009-07-20", Describtion = "hyddd's class")]
    public class MyCode
    {
        //......
    }

プロパティに適用されるターゲット要素を指定した接頭辞で表します.明示的な処理は、可能な二義性を除去することができるため、処理を推奨します.
【2】AttributeTargetsの目標は次のとおりである.
マーク
説明
All
任意のアプリケーション要素に属性を適用できます.
Assembly
プロパティは、プログラムセットに適用できます. 
Class
クラスに属性を適用できます.
Constructor
コンストラクション関数にプロパティを適用できます.
Delegate
委任に属性を適用できます.
Enum
列挙にプロパティを適用できます.
Event
イベントにプロパティを適用できます.
Field
フィールドに属性を適用できます.
GenericParameter
汎用パラメータにプロパティを適用できます.
Interface
インタフェースにプロパティを適用できます.
Method
メソッドにプロパティを適用できます.
Module
Moduleとは、Visual Basic標準モジュールではなく、移植可能な実行可能ファイル(.dllまたは.exe)を指します.
Parameter
パラメータに属性を適用できます.
Property
属性(プロパティ)に属性(Attribute)を適用できます.
ReturnValue
戻り値に属性を適用できます.
Struct
構造に属性、すなわち値タイプを適用できます.
【3】AttributeUsageAttributeの3つのプロパティの説明:
属性名
説明
ValidOn
この位置決めパラメータは、指示された属性(Attribute)を配置できるプログラム要素を指定します.AttributeTargetsの列挙数には、属性(Attribute)を配置できるすべての可能な要素のセットがリストされています.複数のAttributeTargets値をビットOR演算で組み合わせることで、必要な有効なプログラム要素の組合せを取得できます.
AllowMultiple
このネーミングパラメータは、指定されたプログラム要素に対して指示された属性を複数回指定できるかどうかを指定します.
Inherited
この名前付きパラメータは、指定した属性が派生クラスと書き換えメンバーによって継承されるかどうかを指定します.
 
転載は出典を説明してください.ありがとうございます.[hyddd( http://www.cnblogs.com/hyddd/ )]
四.参考資料
【1】 Msdn
【2】『君は知らなければならない。NETの特性と属性』、ブロガーは大変お勧め!
【3】『AttributeはNetプログラミングにおける応用』シリーズ記事