繁体   English   中英

无法读取自定义属性

[英]Cannot read Custom Attributes

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

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

主班

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

属性类别

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

在调试时,控制台说“找不到属性”。
有一个简单的示例可以从自定义属性中获取正确的值吗?

void HelpCommand需要检查一个存储列表中用户存储的变量是否相等,并且LevelRequired中的用户级别是否>。

您尚未在类中声明属性,而是在方法HelpCommand上定义了该HelpCommand 您将必须获取HelpCommandMethodInfo并在其上调用GetCustomAttribute 遵循这些原则。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM