MethodBase.Attributes 屬性

定義

取得與這個方法相關的屬性 (Attribute)。

C#
public abstract System.Reflection.MethodAttributes Attributes { get; }

屬性值

其中一個 MethodAttributes 值。

實作

範例

下列程式代碼範例會顯示使用者定義方法 Mymethod 的屬性。

C#

using System;
using System.Reflection;

class AttributesSample
{
    public void Mymethod (int int1m, out string str2m, ref string str3m)
    {
        str2m = "in Mymethod";
    }

    public static int Main(string[] args)
    {
        Console.WriteLine ("Reflection.MethodBase.Attributes Sample");

        // Get the type.
        Type MyType = Type.GetType("AttributesSample");

        // Get the method Mymethod on the type.
        MethodBase Mymethodbase = MyType.GetMethod("Mymethod");

        // Display the method name.
        Console.WriteLine("Mymethodbase = " + Mymethodbase);

        // Get the MethodAttribute enumerated value.
        MethodAttributes Myattributes = Mymethodbase.Attributes;

        // Display the flags that are set.
        PrintAttributes(typeof(System.Reflection.MethodAttributes), (int) Myattributes);
        return 0;
    }

    public static void PrintAttributes(Type attribType, int iAttribValue)
    {
        if (!attribType.IsEnum)
        {
            Console.WriteLine("This type is not an enum.");
            return;
        }

        FieldInfo[] fields = attribType.GetFields(BindingFlags.Public | BindingFlags.Static);
        for (int i = 0; i < fields.Length; i++)
        {
            int fieldvalue = (int)fields[i].GetValue(null);
            if ((fieldvalue & iAttribValue) == fieldvalue)
            {
                Console.WriteLine(fields[i].Name);
            }
        }
    }
}

此程式碼會產生下列輸出:

Reflection.MethodBase.Attributes 範例

Mymethodbase = Void Mymethod (Int32、System.String ByRef、System.String ByRef)

PrivateScope

FamANDAssem

系列

公用

HideBySig

ReuseSlot

備註

所有成員都有一組屬性,這些屬性定義於特定成員類型。

若要取得 MethodAttributes,請先取得類型。 從類型取得 方法。 從方法取得 MethodAttributes

給實施者的注意事項

Attributes使用 屬性來判斷方法是否為 publicprivatefinalvirtual等等。

適用於

產品 版本
.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 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 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

另請參閱