C# - OS 的入口点检查

C# - Entry point check for OS

所以我的 Program.cs 看起来像这样:

using System;
using System.Windows.Forms;
using myProj.GameScreens;

namespace myProj
{
#if WINDOWS
    /// <summary>
    /// The main class.
    /// </summary>
    public static class Program
    {
        static StartScreen startScreen;
        static MainGame mainGame;

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            mainGame = new MainGame();
            startScreen = new StartScreen();
            Application.EnableVisualStyles();

            if (startScreen.ShowDialog() == DialogResult.OK) mainGame.Run();
        }
    }
#else
    System.Environment.Exit(1);
#endif
}

所以我的问题是我真的可以做这样的事情吗? #else 指令中的代码是否可达?如果应用程序不是从 windows OS 启动的,如何退出?或者我可以使用 Exception 吗? Win32Exception 对其他 OS 不起作用,那我该怎么办?即使没有 #else,代码也会退出吗?

选项#1:如果没有退出应用程序windows

选项 #2:告诉用户该应用需要 windows 并退出(可能是自定义异常?也是首选。)

我有一些代码严重依赖于 [DllImport("user32.dll"],所以我只能使用 windows。是的,您猜对了,它是 Windows MonoGame 入口点 class.

这将不起作用,因为 #if 是一个编译时操作,它会更改可执行文件的生成方式。

如果您在 Windows 上编译它并试图在其他地方 运行 它会尝试(并失败)运行 程序。

您需要为操作系统的 运行 时间检查编写代码。 Environment.OSVersion 属性 可能是您需要的,但它 returns 是您需要解析的字符串。另请注意:

In some cases, the OSVersion property may not return the operating system version that matches the version specified for the Windows Program Compatibility mode feature.

Source

至于你的行为,没有必要明确地调用Exit。如果你什么都不做,你的程序无论如何都会停止。尽管您的测试必须在 inside Main.