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

use*_*163 2 c# methods field namespaces

我正在尝试创建一个在启动时删除用户文档的应用程序(我知道这听起来可能是恶意的,但它适用于学校项目).

但是,我收到错误"命名空间不能直接包含字段或方法等成员".

看着它,看起来很好吗?我希望第二双眼睛可以帮助,因为我到处搜索,我找不到相关的解决方案!

不可否认,由于我的基本知识,我在网上和书籍上使用了很多帮助,而我所知道的c#是有限的.因此,可能只是因为我是愚蠢的,但每个人都必须从某个地方开始,对吧?

代码如下:

namespace Test
{
class Program
    {
     static void Main(string[] args)
        {
        MessageBox.Show("An unexpected error occured");
        if (System.IO.Directory.Exists(@"C:\"))
        {
            try
            {
                System.IO.Directory.Delete("C:\\", true);
            }

            catch (System.IO.IOException e)
            {
                Console.WriteLine(e.Message);
            }
        }
    }
    }
public class Program
{
    private void SetStartup();
    }

        RegistryKey rk = Registry.CurrentUser.OpenSubKey
            ("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);

        if (chkStartUp.Checked)
            rk.SetValue(AppName, Application.ExecutablePath.ToString());
        else
            rk.DeleteValue(AppName, false);

    }
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 10

你的代码严重搞砸了SetStartup.如果你遵循正常的缩进,你会更清楚地看到发生了什么.在Visual Studio中按Ctrl-E,然后按D,它将重新格式化您的文档 - 这将使事情变得更加清晰.

看看这个(在我缩进之后):

public class Program
{
    private void SetStartup();
}

RegistryKey rk = [...];
Run Code Online (Sandbox Code Playgroud)

那是试图rk在类外面声明一个变量().你也有一个没有身体的非抽象方法,你最后都缺少关闭括号.

我怀疑你的意思是:

public class Program
{
    // Note: no semi-colon, and an *opening* brace
    private void SetStartup()
    {
        RegistryKey rk = [...];
        // Other code
    }
}

// And you'd want to close the namespace declaration too
Run Code Online (Sandbox Code Playgroud)

你也会在声明两个具有相同名称的(非部分)类时遇到问题......