关于缺少 "out" 参数的 C# 错误,但代码工作正常

C# error about missing "out" parameter, but the code works fine

我有一个 C# 项目,其中包含如下所示的方法:

bool TheMethod(Type arg, out Type output)

稍后在文件中调用它,它看起来像这样,只有一个参数:

if (TheMethod(someArgument))

并且 VS Code 报告此错误:

There is no argument given that corresponds to the required formal parameter 'output' of 'TheMethod(Type, out Type)' (CS7036) [Managed]

尽管有这个错误,代码编译并运行良好。这是怎么回事?这是代码验证的问题吗?在某些情况下是否需要 out 参数,而在其他情况下不需要?我是否应该编辑代码以使其输出到本地字段,即使我永远不会使用它?

实际代码可以在这里找到:https://github.com/godotengine/godot/blob/master/modules/mono/glue/Managed/Files/MarshalUtils.cs#L156

假设您指的是方法:

static bool GenericIDictionaryIsAssignableFromType(Type type, out Type keyType, out Type valueType)

以及对方法的调用:

#if DEBUG
            if (!GenericIDictionaryIsAssignableFromType(dictionary.GetType()))
                throw new InvalidOperationException("The type does not implement IDictionary<,>");
#endif

那么您看到的行为可能与预处理器指令 (#if/#endif) 的存在有关。如果您在 DEBUG 模式下在本地编译代码,

代码将抛出您所看到的那种编译器错误。但是,如果您 compile/run 处于 RELEASE 模式(这可能是您的 CI/CD and/or 其他测试环境的配置方式),代码将不会有任何错误(因为 #if/#endif在编译器看到它们之前从文件中排除相关代码行)并且它将按预期运行。