문제

Here is my code:

[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.
    }
}

When I set a break point at the WorkAttribute's constructor, I can see the message past in correctly. But after I call GetCustomAttribute, all the fields inside WorkAttribute is null.

도움이 되었습니까?

해결책

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();
            }
        }
    }
}

This code prints "WorkMessage" just fine. Compare your non-posted code. You may be using the wrong method or wrong type or set the Message somewhere else.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top