英語で読む

次の方法で共有


MemberInfo.IsDefined(Type, Boolean) メソッド

定義

派生クラスでオーバーライドされた場合、このメンバーに、指定された型の属性またはその派生型の属性が 1 つ以上適用されているかどうかを示します。

C#
public abstract bool IsDefined(Type attributeType, bool inherit);

パラメーター

attributeType
Type

検索対象のカスタム属性の型。 検索には、派生型が含まれます。

inherit
Boolean

このメンバーの継承チェーンを検索して属性を見つける場合は true。それ以外の場合は false。 プロパティとイベントの場合、このパラメーターは無視されます。

戻り値

このメンバーに、attributeType の 1 つ以上のインスタンスまたはその派生型が適用されている場合は true。それ以外の場合は false

実装

次の例では、指定した属性が指定したメンバーに適用されるかどうかを判断します。

C#
using System;
using System.Reflection;

// Define a custom attribute with one named parameter.
[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute
{
    private string myName;
    public MyAttribute(string name)
    {
        myName = name;
    }
    public string Name
    {
        get
        {
            return myName;
        }
    }
}

// Define a class that has the custom attribute associated with one of its members.
public class MyClass1
{
    [MyAttribute("This is an example attribute.")]
    public void MyMethod(int i)
    {
        return;
    }
}

public class MemberInfo_GetCustomAttributes_IsDefined
{
    public static void Main()
    {
        try
        {
            // Get the type of MyClass1.
            Type myType = typeof(MyClass1);
            // Get the members associated with MyClass1.
            MemberInfo[] myMembers = myType.GetMembers();

            // Display the attributes for each of the members of MyClass1.
            for(int i = 0; i < myMembers.Length; i++)
            {
                // Display the attribute if it is of type MyAttribute.
                if(myMembers[i].IsDefined(typeof(MyAttribute), false))
                {
                    Object[] myAttributes = myMembers[i].GetCustomAttributes(typeof(MyAttribute), false);
                    Console.WriteLine("\nThe attributes of type MyAttribute for the member {0} are: \n",
                        myMembers[i]);
                    for(int j = 0; j < myAttributes.Length; j++)
                        // Display the value associated with the attribute.
                        Console.WriteLine("The value of the attribute is : \"{0}\"",
                            ((MyAttribute)myAttributes[j]).Name);
                }
            }
        }
        catch(Exception e)
        {
            Console.WriteLine("An exception occurred: {0}", e.Message);
        }
    }
}

注釈

このメソッドは、プロパティとイベントの inherit パラメーターを無視します。 プロパティとイベントの属性を継承チェーンで検索するには、 メソッドの適切なオーバーロードを Attribute.IsDefined 使用します。

注意

.NET Framework バージョン 2.0 では、型、メソッド、またはコンストラクターに新しいメタデータ形式で格納されているセキュリティ属性がある場合、このメソッドは を返trueします。 バージョン 2.0 でコンパイルされたアセンブリでは、この形式が使用されます。 以前のバージョンの .NET Framework でコンパイルされた動的アセンブリとアセンブリでは、古い XML 形式が使用されます。 宣言型セキュリティ属性の出力に関するページを参照してください。

適用対象

製品 バージョン
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 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 2.0, 2.1