为什么我的自定义属性参数为null?

时间:2014-03-31 18:03:37

标签: c# custom-attributes

这是我的代码:

[AttributeUsage(AttributeTargets.Method)]
public class WorkAttribute : System.Attribute
{
    public string Message;

    public WorkAttribute(string message)
    {
        this.Message = message;
    }
}

[Work("WorkMessage")]
public void test(){...}

foreach (MethodInfo methodInfo in type.GetMethods())// type is the class's type
{
    WorkAttribute workAttribute = methodInfo.GetCustomAttribute<WorkAttribute>();
    if (workAttribute != null)
    {
        Console.WriteLine(workAttribute.Message);// Should print "WorkMessage", but Message is null.
    }
}

当我在WorkAttribute的构造函数中设置断点时,我可以正确地看到消息过去。但在我调用GetCustomAttribute之后,WorkAttribute中的所有字段都为空。

1 个答案:

答案 0 :(得分:0)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    [AttributeUsage(AttributeTargets.Method)]
    public class WorkAttribute : System.Attribute
    {
        public string Message;

        public WorkAttribute(string message)
        {
            this.Message = message;
        }
    }

    class Program
    {
        [Work("WorkMessage")]
        public void test()
        {
        }

        static void Main()
        {
            foreach (MethodInfo methodInfo in typeof(Program).GetMethods())
            {
                WorkAttribute workAttribute = methodInfo.GetCustomAttribute<WorkAttribute>();
                if (workAttribute != null)
                {
                    Console.WriteLine(workAttribute.Message);// Should print "WorkMessage", but Message is null.
                }

                Console.ReadLine();
            }
        }
    }
}

此代码打印“WorkMessage”就好了。比较您的非发布代码。您可能使用了错误的方法或错误的类型,或者在其他地方设置了消息。