【问题标题】:C# Cant find object reference when using terminal.gui使用 terminal.gui 时 C# 找不到对象引用
【发布时间】:2019-04-14 16:08:40
【问题描述】:

我一直在玩一些服务器/客户端的东西,虽然我尝试使用 terminal.gui,但由于某种原因,我不明白它的作用。我有 2 个脚本;一个处理后端的东西,一个处理用户界面/交互。

脚本1:

using UI;

namespace ServerTest
{
    public class Server
    {
        static void Main() 
        {
            UI.UI.main();
            StartServ();
            RecieveConn.Start();
            MngSockets.Start();
        }
    }
}

脚本 2:

using ServerTest;
using Terminal.Gui;

namespace UI
{
    public class UI
    {
        static Window win = new Window(new Rect(0, 0, Application.Top.Frame.Width, Application.Top.Frame.Height), "MyApp");
        public static void main()
        {
            Application.Init();
            win.Add(new Label(0, 0, "asd"));

            Application.Run(win);
        }
    }
}

这给了我错误:

System.TypeInitializationException
  HResult=0x80131534
  Message=The type initializer for 'UI.UI' threw an exception.
  Source=Server
  StackTrace:
   at UI.UI.main() in C:\Users\ThisPc\Desktop\ConsoleApp2\ConsoleApp2\ui.cs:line 29
   at ServerTest.Server.Main() in C:\Users\ThisPc\Desktop\ConsoleApp2\ConsoleApp2\Program.cs:line 23

Inner Exception 1:
NullReferenceException: Object reference not set to an instance of an object.

不过,如果我这样做,它会起作用:

using ServerTest;
using Terminal.Gui;

namespace UI
{
    public class UI
    {
        public static void main()
        {
            Window win = new Window(new Rect(0, 0, Application.Top.Frame.Width, Application.Top.Frame.Height), "MyApp");

            Application.Init();
            win.Add(new Label(0, 0, "asd"));

            Application.Run(win);
        }
    }
}

但是我不能在其他函数中使用win 变量... 提前致谢 =)

【问题讨论】:

  • 简短的回答是静态构造函数可能运行得太早 - 在 Application 初始化之前。
  • 有道理...非常感谢! =)

标签: c# .net visual-studio user-interface terminal.gui


【解决方案1】:

谢谢mjwills的答案......

只是做

using ServerTest;
using Terminal.Gui;

namespace UI
{
    public class UI
    {
        static Window win = null;
        public static void main()
        {
            win = new Window(new Rect(0, 0, Application.Top.Frame.Width, Application.Top.Frame.Height), "MyApp");

            Application.Init();
            win.Add(new Label(0, 0, "asd"));

            Application.Run(win);
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-20
    • 2017-08-25
    • 2023-03-24
    • 1970-01-01
    相关资源
    最近更新 更多