C# 无法读取自定义属性
我在读取自定义属性时遇到问题。C# 无法读取自定义属性,c#,custom-attributes,C#,Custom Attributes,我在读取自定义属性时遇到问题。 我已经阅读了更多关于这方面的教程,但无法读取值 注意:我使用一个控制台应用程序 主类 namespace IRCBotter { public class IrcBot { [UserLevel(LevelRequired = 10)] void HelpCommand(string user) { GetAttribute(typeof(IrcBot)); }
我已经阅读了更多关于这方面的教程,但无法读取值 注意:我使用一个控制台应用程序 主类
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; }
}
}
在调试时,控制台告诉我“未找到属性”。有一个简单的示例可以从自定义属性获取正确的值吗 在
无效帮助命令中
需要检查存储在一个存储列表中的变量user是否相等
而him级别在LevelRequired中为>。您没有在类中声明属性,而是在方法
HelpCommand
中定义了它。您必须获取HelpCommand
的MethodInfo
,并调用GetCustomAttribute
。沿着这条线的东西
MethodInfo method = type.GetMethod("HelpCommand");
UserLevel userLevel = method.GetCustomAttribute<UserLevel>();
MethodInfo-method=type.GetMethod(“HelpCommand”);
UserLevel UserLevel=method.GetCustomAttribute();
首先,在上课之前,您的属性缺少公共访问修饰符。哪一行有例外?不,没有。但值为空,请自己动手并遵循属性的命名约定。您的类应命名为UserLevelAttribute
。我尝试了tanks danielFixed tanks daniel,但在您的代码中有一个补丁,用于我的GetCustomAttribute();确实有效。只需在object[]userLevel=method.GetCustomAttribute中进行简单编辑(false);