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

C#中使用out变量时遇GetCustomAttribute编译异常问题

解决C#中MethodInfo.GetCustomAttribute编译错误的离奇情况

问题重现

我在实现小型脚本语言时碰到一个诡异的编译错误。核心代码如下:

public void Run()
{
    Dictionary<string, System.Reflection.MethodInfo> data = new();

    if (!data.TryGetValue("foo", out System.Reflection.MethodInfo? methodInfo))
    {
        throw new Exception($"Function '' not found in function map.");
    }

    MiniscriptFunctionAttribute? attribute = methodInfo.GetCustomAttribute<MiniscriptFunctionAttribute>();

    methodInfo.Invoke(vm.Implementation, null);
}

自定义属性类定义:

[AttributeUsage(AttributeTargets.Method)]
public class MiniscriptFunctionAttribute : Attribute
{
    public string Name { get; }
    public int ParamCount { get; }

    public MiniscriptFunctionAttribute(string name, int paramCount)
    {
        Name = name;
        ParamCount = paramCount;
    }
}

编译时触发错误:

12>S:\dfs\saintaveline\MiniscriptConsole\Program.cs(39,65,39,112): error CS1061: 'MethodInfo' does not contain a definition for 'GetCustomAttribute' and no accessible extension method 'GetCustomAttribute' accepting a first argument of type 'MethodInfo' could be found (are you missing a using directive or an assembly reference?)

更奇怪的是,把调用GetCustomAttribute的代码复制一份(命名变量为attribute2)后错误自动消失;即便删除新复制的代码,原错误也不再出现。

原因分析

这种异常情况主要有两类可能:

  1. 基础依赖缺失:GetCustomAttribute是MemberInfo(MethodInfo的父类)的扩展方法,定义在System.Reflection命名空间下,如果没引入这个命名空间,编译器会找不到方法。
  2. IDE/编译器缓存异常:Visual Studio的Roslyn代码分析器或项目缓存偶尔会出现状态错乱,导致错误提示异常。

解决步骤

  1. 检查命名空间
    确认代码文件顶部是否添加了:

    using System.Reflection;
    

    没有的话添加上,再重新编译。

  2. 清理项目缓存

    • Visual Studio界面操作:点击「生成」→「清理解决方案」,接着「生成解决方案」;或者右键项目→「卸载项目」→「重新加载项目」。
    • dotnet CLI操作:执行以下命令:
      dotnet clean
      dotnet build
      
  3. 重启IDE
    有时候VS的代码分析器会陷入临时异常状态,重启IDE就能恢复正常。

  4. 版本排查
    如果以上步骤都无效,尝试更新Visual Studio到最新稳定版,或者新建一个空白项目复制代码验证,排除项目配置损坏的可能。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.02 03:37:28