You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

控制台程序中读取自定义Custom Attributes失败问题求助

解决自定义属性读取失败的问题

看起来你遇到的核心问题是找错了自定义属性的载体,同时属性类的访问权限也需要调整。我来帮你一步步修正:

问题分析

你的[UserLevel]属性是标记在HelpCommand方法上的,但你在GetAttribute里传入的是typeof(IrcBot)(类的Type),这相当于在类的级别去查找属性,自然找不到方法上的标记。另外你的UserLevel属性类没有加public修饰符,默认是internal,虽然在同一程序集内可能能访问,但显式声明更稳妥,也避免跨命名空间的潜在问题。

修正步骤

1. 完善属性类

首先补全属性类的访问修饰符和属性的getter/setter:

namespace IRCBotter.Commands {
    // 既然是标记方法,把AttributeTargets改成Method更严谨(如果需要标记其他类型可以保留All)
    [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
    public class UserLevel : Attribute {
        public int LevelRequired { get; set; }
    }
}

2. 调整属性读取逻辑

修改GetAttribute方法,让它接收方法的MethodInfo,而不是类的Type,同时在HelpCommand里正确获取当前方法的信息:

namespace IRCBotter {
    public class IrcBot {
        [UserLevel(LevelRequired = 10)]
        void HelpCommand(string user) {
            // 获取HelpCommand方法的MethodInfo,注意方法是private的,要指定BindingFlags
            var method = typeof(IrcBot).GetMethod(
                nameof(HelpCommand), 
                BindingFlags.Instance | BindingFlags.NonPublic
            );
            GetAttribute(method);
        }

        public static void GetAttribute(System.Reflection.MethodInfo methodInfo) {
            // 从方法上获取自定义属性
            UserLevel MyAttribute = (UserLevel)Attribute.GetCustomAttribute(methodInfo, typeof(UserLevel));
            if (MyAttribute == null) {
                Message.Error("The attribute was not found.");
            } else {
                Message.Error("Valore " + MyAttribute.LevelRequired.ToString());
            }
        }
    }
}

关键注意点

  • 绑定标志(BindingFlags):因为HelpCommand是私有方法,所以调用GetMethod时必须加上BindingFlags.Instance | BindingFlags.NonPublic,否则会返回null。
  • 属性载体匹配:一定要确保你获取属性的对象(类、方法、字段等)和你标记属性的对象一致,比如标记在方法上就找方法的MethodInfo,标记在类上就找类的Type。

内容的提问来源于stack exchange,提问作者giovanni mannuoio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:12:35