错误:命名空间不能直接包含字段或方法等成员

我是C#的新手,我在解决这个错误时遇到问题,任何人都可以帮助我吗? 此脚本用于删除不需要的快捷方式,然后安装新程序(如果尚未安装)。

using System; using WindowsInstaller; string startMenuDir = Environment.GetFolderPath(Environment.SpecialFolder.StartMenu); string shortcutold = Path.Combine(startMenuDir, @"Ohal\TV AMP (Windows XP Mode).lnk"); if (File.Exists(shortcutold)) File.Delete(shortcutold); string startMenuDir = Environment.GetFolderPath(Environment.SpecialFolder.StartMenu); string shortcut = Path.Combine(startMenuDir, @"Ohal\TV AMP.lnk"); if (File.Exists(shortcut)) { Console.WriteLine("Already installed..."); } else { Type type = Type.GetTypeFromProgID("WindowsInstaller.Installer"); Installer installer = (Installer)Activator.CreateInstance(type); installer.InstallProduct(@"Y:\LibSetup\TVAMP313\TVAmp v3.13.msi"); } 

您的代码应该在类中,然后是方法。 您不能在命名空间下拥有代码。 跟随之类的东西。

 using System; using WindowsInstaller; class MyClass //Notice the class { //You can have fields and properties here public void MyMethod() // then the code in a method { string startMenuDir = Environment.GetFolderPath(Environment.SpecialFolder.StartMenu); string shortcutold = Path.Combine(startMenuDir, @"Ohal\TV AMP (Windows XP Mode).lnk"); if (File.Exists(shortcutold)) File.Delete(shortcutold); // your remaining code ......... } } 

正如Habib所说,你需要将代码放在方法,构造函数等中。在这种情况下,如果你想要的代码就是你想要的入口点,你只需要:

 using System; using WindowsInstaller; class Program { // Or static void Main(string[] args) to use command line arguments static void Main() { string startMenuDir = ...; string shortcutold = ...; // Rest of your code } } 

基本上, Main方法是独立C#程序的入口点。

当然,如果你的代码是其他东西的插件,你可能需要实现一个接口或类似的东西。 无论哪种方式,您都必须将您的代码放在成员中,而不仅仅是“裸露”。

这很可能是你打算做的:

 using System; using WindowsInstaller; namespace DataImporter { class Program { static void Main(string[] args) { string startMenuDir = Environment.GetFolderPath(Environment.SpecialFolder.StartMenu); string shortcutold = Path.Combine(startMenuDir, @"Ohal\TV AMP (Windows XP Mode).lnk"); if (File.Exists(shortcutold)) File.Delete(shortcutold); string startMenuDir = Environment.GetFolderPath(Environment.SpecialFolder.StartMenu); string shortcut = Path.Combine(startMenuDir, @"Ohal\TV AMP.lnk"); if (File.Exists(shortcut)) { Console.WriteLine("Already installed..."); } else { Type type = Type.GetTypeFromProgID("WindowsInstaller.Installer"); Installer installer = (Installer)Activator.CreateInstance(type); installer.InstallProduct(@"Y:\LibSetup\TVAMP313\TVAmp v3.13.msi"); } } } } 

您的方法必须现在在类中这是在命名空间中,您必须在此命名空间中声明一个类,然后在此类中声明方法