选项属性未按预期设置默认值[重复]

问题描述 投票:1回答:1

我只是使用NuGet包CommandLineParser向我的应用程序添加可选的命令行参数支持。我正在将Options类对象传递到主应用程序中,以便可以根据需要访问该对象的必要值。

问题...

  1. 我将Options类移到静态类Program之外的唯一原因是,我可以在应用程序的其他部分中创建一个称为Options的变量,并知道Options类。这样做时,我现在收到以下错误。我注意到,选项属性'Filepath'在技术上应为空字符串时返回null。为什么我的Default =“”无法正常工作?

'System.NullReferenceException:'对象引用未设置为对象的实例。'Snipper.Options.Filepath.get返回null

enter image description here

using System;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;
using CommandLine;


    namespace Snipper
    {
        public class Options
        {   
            [Option('f', "filepath", Default = "", Required = false, HelpText = "Set output path, otherwise save in Pictures/Snipper")]
            public string Filepath { get; set; }

            [Option('w', "width", Default = 0, Required = false, HelpText = "Final output resolution width in pixels")]
            public int Width { get; set; }

            [Option('h', "height", Default = 0, Required = false, HelpText = "Final output resolution height in pixels")]
            public int Height { get; set; }
        }

        static class Program
        {
            /// <summary>
            /// The main entry point for the application.
            /// </summary>
            [STAThread]
            static void Main(string[] args)
            {
                // do not allow multiple instances of the same program
                if (Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).Length > 1)
                {
                    return;
                }

                // Commandline args
                var options = new Options();
                Parser.Default.ParseArguments<Options>(args).WithParsed<Options>(opts => options = opts);

                if (options.Filepath.Trim() == "")
                {
                    options.Filepath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), "Snipper", "screenshot.png");
                }

                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new MainForm(options));
            }
        }
    }
c# command-line-arguments
1个回答
0
投票

您确定是options而不是Filepathnull吗? (编辑:我确定是您发布的屏幕警告中的Filepath

[尝试用!(String.IsNullOrWhitespace(options?.Filepath))替换违规行

© www.soinside.com 2019 - 2024. All rights reserved.