英語で読む

次の方法で共有


CustomAttributeNamedArgument 構造体

定義

リフレクションのみのコンテキストのカスタム属性の名前付き引数を表します。

C#
public struct CustomAttributeNamedArgument
C#
public readonly struct CustomAttributeNamedArgument : IEquatable<System.Reflection.CustomAttributeNamedArgument>
C#
public readonly struct CustomAttributeNamedArgument
C#
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public struct CustomAttributeNamedArgument
継承
CustomAttributeNamedArgument
属性
実装

次の例では、4 つのコンストラクターと 4 つのプロパティを持つカスタム属性を定義します。 2 つのプロパティは読み取り専用であり、コンストラクターの位置パラメーターを使用して設定されます。 他の 2 つのプロパティは読み取り/書き込みであり、名前付き引数を使用してのみ設定できます。 位置指定プロパティの 1 つは文字列の配列であり、1 つの名前付きプロパティは整数の配列です。

この属性は、アセンブリ、アセンブリで宣言された型、型のメソッド、およびメソッドのパラメーターに適用されます。 このような場合は、さまざまなコンストラクターが使用されます。 実行時に、アセンブリはリフレクションのみのコンテキストに自身を読み込み、それに適用されたカスタム属性と、それに含まれる型とメンバーに関する情報を表示します。

型に適用される属性は、位置引数と名前付き引数の両方を持つ配列プロパティを示しています。

C#
using System;
using System.Reflection;
using System.Collections.Generic;
using System.Collections.ObjectModel;

// The example attribute is applied to the assembly.
[assembly:Example(ExampleKind.ThirdKind, Note="This is a note on the assembly.")]

// An enumeration used by the ExampleAttribute class.
public enum ExampleKind
{
    FirstKind,
    SecondKind,
    ThirdKind,
    FourthKind
};

// An example attribute. The attribute can be applied to all
// targets, from assemblies to parameters.
//
[AttributeUsage(AttributeTargets.All)]
public class ExampleAttribute : Attribute
{
    // Data for properties.
    private ExampleKind kindValue;
    private string noteValue;
    private string[] arrayStrings;
    private int[] arrayNumbers;

    // Constructors. The parameterless constructor (.ctor) calls
    // the constructor that specifies ExampleKind and an array of
    // strings, and supplies the default values.
    //
    public ExampleAttribute(ExampleKind initKind, string[] initStrings)
    {
        kindValue = initKind;
        arrayStrings = initStrings;
    }
    public ExampleAttribute(ExampleKind initKind) : this(initKind, null) {}
    public ExampleAttribute() : this(ExampleKind.FirstKind, null) {}

    // Properties. The Note and Numbers properties must be read/write, so they
    // can be used as named parameters.
    //
    public ExampleKind Kind { get { return kindValue; }}
    public string[] Strings { get { return arrayStrings; }}
    public string Note
    {
        get { return noteValue; }
        set { noteValue = value; }
    }
    public int[] Numbers
    {
        get { return arrayNumbers; }
        set { arrayNumbers = value; }
    }
}

// The example attribute is applied to the test class.
//
[Example(ExampleKind.SecondKind,
         new string[] { "String array argument, line 1",
                        "String array argument, line 2",
                        "String array argument, line 3" },
         Note="This is a note on the class.",
         Numbers = new int[] { 53, 57, 59 })]
public class Test
{
    // The example attribute is applied to a method, using the
    // parameterless constructor and supplying a named argument.
    // The attribute is also applied to the method parameter.
    //
    [Example(Note="This is a note on a method.")]
    public void TestMethod([Example] object arg) { }

    // Main() gets objects representing the assembly, the test
    // type, the test method, and the method parameter. Custom
    // attribute data is displayed for each of these.
    //
    public static void Main()
    {
        Assembly asm = Assembly.ReflectionOnlyLoad("Source");
        Type t = asm.GetType("Test");
        MethodInfo m = t.GetMethod("TestMethod");
        ParameterInfo[] p = m.GetParameters();

        Console.WriteLine("\r\nAttributes for assembly: '{0}'", asm);
        ShowAttributeData(CustomAttributeData.GetCustomAttributes(asm));
        Console.WriteLine("\r\nAttributes for type: '{0}'", t);
        ShowAttributeData(CustomAttributeData.GetCustomAttributes(t));
        Console.WriteLine("\r\nAttributes for member: '{0}'", m);
        ShowAttributeData(CustomAttributeData.GetCustomAttributes(m));
        Console.WriteLine("\r\nAttributes for parameter: '{0}'", p);
        ShowAttributeData(CustomAttributeData.GetCustomAttributes(p[0]));
    }

    private static void ShowAttributeData(
        IList<CustomAttributeData> attributes)
    {
        foreach( CustomAttributeData cad in attributes )
        {
            Console.WriteLine("   {0}", cad);
            Console.WriteLine("      Constructor: '{0}'", cad.Constructor);

            Console.WriteLine("      Constructor arguments:");
            foreach( CustomAttributeTypedArgument cata
                in cad.ConstructorArguments )
            {
                ShowValueOrArray(cata);
            }

            Console.WriteLine("      Named arguments:");
            foreach( CustomAttributeNamedArgument cana
                in cad.NamedArguments )
            {
                Console.WriteLine("         MemberInfo: '{0}'",
                    cana.MemberInfo);
                ShowValueOrArray(cana.TypedValue);
            }
        }
    }

    private static void ShowValueOrArray(CustomAttributeTypedArgument cata)
    {
        if (cata.Value.GetType() == typeof(ReadOnlyCollection<CustomAttributeTypedArgument>))
        {
            Console.WriteLine("         Array of '{0}':", cata.ArgumentType);

            foreach (CustomAttributeTypedArgument cataElement in
                (ReadOnlyCollection<CustomAttributeTypedArgument>) cata.Value)
            {
                Console.WriteLine("             Type: '{0}'  Value: '{1}'",
                    cataElement.ArgumentType, cataElement.Value);
            }
        }
        else
        {
            Console.WriteLine("         Type: '{0}'  Value: '{1}'",
                cata.ArgumentType, cata.Value);
        }
    }
}

/* This code example produces output similar to the following:

Attributes for assembly: 'source, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'
   [System.Runtime.CompilerServices.CompilationRelaxationsAttribute((Int32)8)]
      Constructor: 'Void .ctor(Int32)'
      Constructor arguments:
         Type: 'System.Int32'  Value: '8'
      Named arguments:
   [System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows = True)]
      Constructor: 'Void .ctor()'
      Constructor arguments:
      Named arguments:
         MemberInfo: 'Boolean WrapNonExceptionThrows'
         Type: 'System.Boolean'  Value: 'True'
   [ExampleAttribute((ExampleKind)2, Note = "This is a note on the assembly.")]
      Constructor: 'Void .ctor(ExampleKind)'
      Constructor arguments:
         Type: 'ExampleKind'  Value: '2'
      Named arguments:
         MemberInfo: 'System.String Note'
         Type: 'System.String'  Value: 'This is a note on the assembly.'

Attributes for type: 'Test'
   [ExampleAttribute((ExampleKind)1, new String[3] { "String array argument, line 1", "String array argument, line 2", "String array argument, line 3" }, Note = "This is a note on the class.", Numbers = new Int32[3] { 53, 57, 59 })]
      Constructor: 'Void .ctor(ExampleKind, System.String[])'
      Constructor arguments:
         Type: 'ExampleKind'  Value: '1'
         Array of 'System.String[]':
             Type: 'System.String'  Value: 'String array argument, line 1'
             Type: 'System.String'  Value: 'String array argument, line 2'
             Type: 'System.String'  Value: 'String array argument, line 3'
      Named arguments:
         MemberInfo: 'System.String Note'
         Type: 'System.String'  Value: 'This is a note on the class.'
         MemberInfo: 'Int32[] Numbers'
         Array of 'System.Int32[]':
             Type: 'System.Int32'  Value: '53'
             Type: 'System.Int32'  Value: '57'
             Type: 'System.Int32'  Value: '59'

Attributes for member: 'Void TestMethod(System.Object)'
   [ExampleAttribute(Note = "This is a note on a method.")]
      Constructor: 'Void .ctor()'
      Constructor arguments:
      Named arguments:
         MemberInfo: 'System.String Note'
         Type: 'System.String'  Value: 'This is a note on a method.'

Attributes for parameter: 'System.Object arg'
   [ExampleAttribute()]
      Constructor: 'Void .ctor()'
      Constructor arguments:
      Named arguments:
*/

注釈

リフレクションのみのコンテキストで調べられているコードは実行できないため、カスタム属性のインスタンスを作成し、Attribute.GetCustomAttributesMemberInfo.GetCustomAttributesなどのメソッドを使用してプロパティを調べることで、カスタム属性を調べることは常に不可能です。 属性型自体のコードがリフレクションのみのコンテキストに読み込まれている場合は、実行できません。

CustomAttributeNamedArgument 構造体は、カスタム属性の型の対応するプロパティのコードを実行せずに、カスタム属性インスタンスに指定された名前付き引数へのアクセスを提供するために、CustomAttributeData クラスによって使用されます。 TypedValue プロパティは、名前付き引数の型と値を含む CustomAttributeTypedArgument 構造体を返します。

重要

引数に名前が付けられているか位置指定されているかに関係なく、CustomAttributeTypedArgument 構造体を使用して、その型と値にアクセスする必要があります。

CustomAttributeData クラスのインスタンスを作成するには、staticGetCustomAttributes ファクトリ メソッドを使用します。

コンストラクター

CustomAttributeNamedArgument(MemberInfo, CustomAttributeTypedArgument)

カスタム属性の指定したフィールドまたはプロパティを表す CustomAttributeNamedArgument クラスの新しいインスタンスを初期化し、フィールドまたはプロパティの型と値を記述する CustomAttributeTypedArgument オブジェクトを指定します。

CustomAttributeNamedArgument(MemberInfo, Object)

カスタム属性の指定したフィールドまたはプロパティを表す CustomAttributeNamedArgument クラスの新しいインスタンスを初期化し、フィールドまたはプロパティの値を指定します。

プロパティ

IsField

名前付き引数がフィールドかどうかを示す値を取得します。

MemberInfo

名前付き引数の設定に使用される属性メンバーを取得します。

MemberName

名前付き引数の設定に使用される属性メンバーの名前を取得します。

TypedValue

現在の名前付き引数の型と値を取得するために使用できる CustomAttributeTypedArgument 構造体を取得します。

メソッド

Equals(CustomAttributeNamedArgument)

現在のインスタンスが同じ型の別のインスタンスと等しいかどうかを示します。

Equals(Object)

このインスタンスが指定したオブジェクトと等しいかどうかを示す値を返します。

GetHashCode()

このインスタンスのハッシュ コードを返します。

ToString()

引数の名前、等号、および引数値の文字列表現で構成される文字列を返します。

演算子

Equality(CustomAttributeNamedArgument, CustomAttributeNamedArgument)

2 つの CustomAttributeNamedArgument 構造体が等しいかどうかをテストします。

Inequality(CustomAttributeNamedArgument, CustomAttributeNamedArgument)

2 つの CustomAttributeNamedArgument 構造が異なるかどうかをテストします。

適用対象

製品 バージョン
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

こちらもご覧ください