繁体   English   中英

C# 代码显示错误“命名空间不能直接包含成员,如字段或方法”

[英]C# code showing error "A namespace cannot directly contain members such as fields or methods"

我不知道为什么会弹出这个错误我没有在课堂外声明任何东西我的完整代码是这样的:

using System;
using Microsoft.CSharp;
using System.IO;
using System.CodeDom.Compiler;
using System.Text;

namespace test
  {
  public class comp
   {
    static void Main()
    {
        string code="0x4d,0x41,0x2......"; //and soo onnn
        string Arch = " /platform:x86 /optimize";
        string filePath = "C:/menmon.exe";
        CSharpCodeProvider provider = new CSharpCodeProvider();
        CompilerParameters parameters = new CompilerParameters();

        parameters.ReferencedAssemblies.Add("System.Core.dll");
        parameters.GenerateInMemory = false;
        parameters.GenerateExecutable = true;
        parameters.IncludeDebugInformation = false;
        parameters.ReferencedAssemblies.Add("mscorlib.dll");
        parameters.ReferencedAssemblies.Add("System.dll");

        parameters.OutputAssembly = filePath;
        parameters.CompilerOptions = "/target:exe" + Arch;
        CompilerResults results = provider.CompileAssemblyFromSource(parameters, code);
        if (results.Errors.HasErrors)
        {
        StringBuilder sb = new StringBuilder();
        foreach (CompilerError error in results.Errors)
          {
            sb.AppendLine(String.Format("Error ({0}): {1}", error.ErrorNumber, error.ErrorText));
          }
        }

        throw new InvalidOperationException(sb.ToString());
      }
    }
  } 

}

在 .Net framework64 v4.0.30319 上的 Windows 机器上使用 cmd 编译这个错误在编译后发生(编译时没有显示错误),当我运行程序时会弹出这个错误:

未处理的异常:System.InvalidOperationException:错误 (CS0116):命名空间不能直接包含成员,如字段或方法

在 comp.Main()

我像这样运行 csc.exe

csc /t:exe /out:"C:\\output.exe" "C:\\input.cs"

不确定这对你有帮助,但你能不能尝试在类的前面添加你的应用程序的命名空间,这样它看起来像这样:

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
        }
    }
}

此外,您在 main 函数的最后一行缺少分号。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM