无法读取自定义属性

Cannot read Custom Attributes

我在读取自定义属性时遇到问题。
我已经阅读了更多教程,但无法读取值。

注意:我使用控制台应用程序。

主要Class

namespace IRCBotter
{
    public class IrcBot
    {
        [UserLevel(LevelRequired = 10)]
        void HelpCommand(string user)
        {
            GetAttribute(typeof(IrcBot));
        }

        public static void GetAttribute(Type t)
        {
            // Get instance of the attribute.
            UserLevel MyAttribute =
                   (UserLevel)Attribute.GetCustomAttribute(t, typeof(UserLevel));

               if (MyAttribute == null)
               {
                   Message.Error("The attribute was not found.");
               }
               else
               {
                   // Get the Name value.
                   Message.Error("Valore " + MyAttribute.LevelRequired.ToString());
               }
           }
     }
}

属性Class

namespace IRCBotter.Commands
{
    [AttributeUsage(AttributeTargets.All ,AllowMultiple=true)]
    class UserLevel : Attribute
    {
        public int LevelRequired { get; set; }
    }
}

在调试时,控制台说我 "The attribute was not found"。
有一个简单的工作示例可以从自定义属性中获取正确的值吗?

void HelpCommand 需要检查变量用户存储在一个存储列表中是否相等 他的等级 > 在 LevelRequired.

您尚未在 class 上声明属性,您在方法 HelpCommand 上定义了它。您必须为 HelpCommand 获取 MethodInfo 并调用 GetCustomAttribute。沿着这些路线。

MethodInfo method = type.GetMethod("HelpCommand");
UserLevel userLevel = method.GetCustomAttribute<UserLevel>();