首页主机资讯C#中GetCustomAttributes如何获取参数属性

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

时间2024-08-19 16:08:03发布访客分类主机资讯浏览851
导读:在C#中,您可以使用GetCustomAttributes方法来获取指定成员(如类、方法、属性等)的自定义属性。这个方法接受一个Type参数,用于指定要获取的属性的类型。以下是一个示例代码,演示如何获取参数的属性: using System...

在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方法获取参数的属性,并输出每个参数及其属性的值。

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: C#中GetCustomAttributes如何获取参数属性
本文地址: https://pptw.com/jishu/694533.html
C#中float类型数据的四舍五入方法有哪些 C#中GetCustomAttributes如何获取成员属性

游客 回复需填写必要信息