溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

C#的System.CommandLine怎么使用

發(fā)布時(shí)間:2022-10-21 09:51:05 來(lái)源:億速云 閱讀:150 作者:iii 欄目:編程語(yǔ)言

本篇內(nèi)容主要講解“C#的System.CommandLine怎么使用”,感興趣的朋友不妨來(lái)看看。本文介紹的方法操作簡(jiǎn)單快捷,實(shí)用性強(qiáng)。下面就讓小編來(lái)帶大家學(xué)習(xí)“C#的System.CommandLine怎么使用”吧!

System.CommandLine,通過(guò)他我們可以幾乎無(wú)需任何額外的編碼就可以獲得命令行的支持,它能大幅減少程序員花在提供命令行API(CLI)上的時(shí)間,改善CLI程序用戶的體驗(yàn),讓開發(fā)者能專注于編寫應(yīng)用程序。

目前這個(gè)庫(kù)還是預(yù)覽版本,要體驗(yàn)的話需要可以使用如下庫(kù):System.CommandLine.DragonFruit。首先以一個(gè)簡(jiǎn)單的示例來(lái)演示它的功能。

static void Main(string input, string output)
{
    Console.WriteLine($"Input: {input}, Output: {output}");
}

這里我們并沒有要顯式使用這個(gè)庫(kù),只需要將Main函數(shù)的入?yún)⒏某晌覀冃枰褂玫念愋?,程序便自?dòng)實(shí)現(xiàn)了命令行的支持。我們甚至可以用—help查看程序的命令行的配置方式

    ConsoleApp1.exe --help
    Usage:
     ConsoleApp1 [options]
    Options:
     --input <INPUT> input
     --output <OUTPUT> output
     --version Display version information

可見,它能自動(dòng)根據(jù)Main函數(shù)的參數(shù)自動(dòng)解析出命令行的格式,并生成幫助文檔。

接著,我們?cè)賮?lái)看看命令行的使用:

    ConsoleApp1 --input ii --output out
    Input: ii, Output: out

完美的進(jìn)行了命令行的解析,它也可以讀取xml注釋,實(shí)現(xiàn)更加復(fù)雜的說(shuō)明。

/// <summary>
/// Converts an image file from one format to another.
/// </summary>
/// <param name="input">The path to the image file that is to be converted.</param>
/// <param name="output">The name of the output from the conversion.</param>
/// <param name="xCropSize">The x dimension size to crop the picture. The default is 0 indicating no cropping is required.</param>
/// <param name="yCropSize">The x dimension size to crop the picture. The default is 0 indicating no cropping is required.</param>
static void Main(string input, string output, int xCropSize = 0, int yCropSize = 0)
{
}

生成的幫助輸出效果如下:

    ConsoleApp1:
     Converts an image file from one format to another.
    Usage:
     ConsoleApp1 [options]
    Options:
     --input <INPUT> The path to the image file that is to be converted.
     --output <OUTPUT> The name of the output from the conversion.
     --x-crop-size <X-CROP-SIZE> The x dimension size to crop the picture. The default is 0 indicating no cropping is required.
     --y-crop-size <Y-CROP-SIZE> The x dimension size to crop the picture. The default is 0 indicating no cropping is required.
     --version Display version information

相比傳統(tǒng)的命令行庫(kù),這個(gè)庫(kù)的優(yōu)勢(shì)非常明顯,我們可以幾乎不編寫任何代碼就可以獲得命令行程序的支持。對(duì)于復(fù)雜的命令行程序來(lái)說(shuō),可能這里的方式并不能滿足需求。System.CommandLine雖然也支持像傳統(tǒng)命令行的庫(kù)那樣編寫復(fù)雜的命令行支持程序。

到此,相信大家對(duì)“C#的System.CommandLine怎么使用”有了更深的了解,不妨來(lái)實(shí)際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI