我只是使用NuGet包CommandLineParser向我的应用程序添加可选的命令行参数支持。我正在将Options类对象传递到主应用程序中,以便可以根据需要访问该对象的必要值。
问题...
'System.NullReferenceException:'对象引用未设置为对象的实例。'Snipper.Options.Filepath.get返回null
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));
}
}
}
您确定是options
而不是Filepath
是null
吗? (编辑:我确定是您发布的屏幕警告中的Filepath
)
[尝试用!(String.IsNullOrWhitespace(options?.Filepath))
替换违规行