温馨提示×

C#中GetCustomAttributes如何获取参数属性

c#
小樊
90
2024-08-19 13:12:31
栏目: 编程语言

在C#中,您可以使用GetCustomAttributes方法来获取指定成员(如类、方法、属性等)的自定义属性。这个方法接受一个Type参数,用于指定要获取的属性的类型。以下是一个示例代码,演示如何获取参数的属性:

using System;
using System.Reflection;

class Program
{
    static void Main()
    {
        // 获取方法的参数信息
        MethodInfo methodInfo = typeof(Program).GetMethod("MyMethod");
        ParameterInfo[] parameters = methodInfo.GetParameters();

        // 循环遍历方法的参数,获取每个参数的属性
        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方法的参数。然后使用GetCustomAttributes方法获取参数的属性,并输出每个参数及其属性的值。

0