溫馨提示×

C#中GetCustomAttributes如何獲取參數(shù)屬性

c#
小樊
90
2024-08-19 13:12:31
欄目: 編程語言

在C#中,您可以使用GetCustomAttributes方法來獲取指定成員(如類、方法、屬性等)的自定義屬性。這個方法接受一個Type參數(shù),用于指定要獲取的屬性的類型。以下是一個示例代碼,演示如何獲取參數(shù)的屬性:

using System;
using System.Reflection;

class Program
{
    static void Main()
    {
        // 獲取方法的參數(shù)信息
        MethodInfo methodInfo = typeof(Program).GetMethod("MyMethod");
        ParameterInfo[] parameters = methodInfo.GetParameters();

        // 循環(huán)遍歷方法的參數(shù),獲取每個參數(shù)的屬性
        foreach (ParameterInfo parameter in parameters)
        {
            object[] attributes = parameter.GetCustomAttributes(typeof(MyAttribute), true);
            foreach (MyAttribute attribute in attributes)
            {
                Console.WriteLine("Parameter {0} has attribute {1}", parameter.Name, attribute.SomeProperty);
            }
        }
    }

    public static void MyMethod([My("Attribute1")] int param1, [My("Attribute2")] string param2)
    {
        // do something
    }
}

[AttributeUsage(AttributeTargets.Parameter)]
class MyAttribute : Attribute
{
    public string SomeProperty { get; set; }

    public MyAttribute(string propertyValue)
    {
        this.SomeProperty = propertyValue;
    }
}

在上面的示例中,我們定義了一個自定義屬性MyAttribute,并將其應用于MyMethod方法的參數(shù)。然后使用GetCustomAttributes方法獲取參數(shù)的屬性,并輸出每個參數(shù)及其屬性的值。

0