Debug.WriteLine(string, params object[]) 是一种方法,但像类型一样使用

Debug.WriteLine(string, params object[]) is a method but is used like a type

我目前正在做一个待办事项列表项目,我正处于开发的最后阶段,但是我输出到调试的语法似乎不正确,我不确定错误是什么,我们将不胜感激。

如上图,错误为CS0118:

'System.Diagnostics.Debug.WriteLine(string, params object[]) is a method but is used like a type'

#define testing
using System;
using System.Collections.Generic;
using System.Diagnostics;

#if(testing)
    public static string[] tempStringArr = new string[5] 
        { "Hey", "Greetings", "Hello", "Hi", "Example" };
    public static string tempKey = "Hello";

    public static int linearSearchTitleTest(string titleKey, string[] titleArr)
    { 
        for (int i = 0; i < titleArr.Length - 1; i++)
        {
            if (titleKey == titleArr[i])
            {
                return i;
            }
        }
        return -1;
    }

    int testResult = linearSearchTitleTest(tempKey, tempStringArr);
    Debug.WriteLine(Convert.ToString(testResult));
#endif

您的 Debug.WriteLine 调用不在函数范围内。尝试将此代码放入一个函数中,也许在 main() 中用于测试目的?

int testResult = linearSearchTitleTest(tempKey, tempStringArr);
Debug.WriteLine(Convert.ToString(testResult));

例如:

class Program
{
    public static string[] tempStringArr = new string[5] { "Hey", "Greetings", "Hello", "Hi", "Example" };
    public static string tempKey = "Hello";

    static void Main(string[] args)
    {
        int testResult = linearSearchTitleTest(tempKey, tempStringArr);
        Debug.WriteLine(Convert.ToString(testResult));
    }

    public static int linearSearchTitleTest(string titleKey, string[] titleArr)
    {
        for (int i = 0; i < titleArr.Length - 1; i++)
        {
            if (titleKey == titleArr[i])
            {
                return i;
            }
        }
        return -1;
    }
}

C# 是一种 objective 语言。含义:所有代码都必须是对象的一部分。

尝试将您的代码包装在命名空间、class 和方法中。通常是这样的

namespace MyApp
{
    class Program
    {
        static void Main(string[] args)
        {
            // your code here ...
        }
    }
}

实际上,通过使用条件编译,您是在告诉编译器您要编译代码的哪些部分以及不想编译哪些部分,显然这些部分不会以任何形式出现在最终编译文件中。您可以使用反射器和其他 IL 预览工具来检查它。

尽管如此,在包含和排除这些部分之后,您的代码在编译器视图中的格式应该正确,否则编译器无法完成工作。

换句话说,#if#else#endif 不能也不会改变编译器的行为,但它们会在任何编译发生之前更改代码。