简体   繁体   English

在c#控制台应用程序中的多个可选参数之间进行区分

[英]Distinguish between multiple optional arguments in c# Console App

I've read a number of articles on SoF about this, but funny enough, I feel that there is not concise answer. 我已经读过许多关于SoF的文章,但是很有趣,我觉得答案不明确。 Maybe I just haven't found the correct post yet. 也许我只是找不到正确的帖子。

I want to know the best way on how to distinguish between multiple optional parameters when calling your c# console app. 我想知道在调用c#控制台应用程序时如何区分多个可选参数的最佳方法。

Eg. 例如。 Calling MyApp value1 [value2] [value3] [value4] [value5] 调用MyApp value1 [value2] [value3] [value4] [value5]

This app can be called by using 0 - n of the optional arguments like: 可以使用0-n的可选参数来调用此应用,例如:

c:\MyApp.exe value1 value2 value3
c:\MyApp.exe value1 value4 value5
c:\MyApp.exe value1 value4

etc... 等等...

I can extract the arguments with 我可以用提取参数

var argValue = args[1]

but how can I know which of all these optional arguments were actually used? 但是我怎么知道所有这些可选参数中的哪个被实际使用呢?

Should I just prefix them with a predefined label like: 我是否应该给它们加上预定义标签,例如:

c:\MyApp.exe value1 myArg4:value4 myArg5:value5

Yes, you need to provide some way of saying which value is which - just like you would for named arguments in a method call. 是的,您需要提供某种方式来说明哪个值是哪个值-就像您在方法调用中为命名参数一样。 The common conventions are: 通用约定为:

--myArg4=value4
--myArg4 value4

(Some tools prefer -- , others prefer - .) (某些工具更喜欢-- ,其他工具更喜欢- 。)

There isn't anything built into the framework to do this very simply, but the commandline library is very easy to include (just as a source inclusion - you don't need it to be a separate class library). 框架中没有任何东西可以很简单地做到这一点,但是命令行库却很容易包含(就像源代码包含一样,您不需要将其作为单独的类库)。 We use this for Noda Time for all our command-line tools. 我们将其用于所有命令行工具的Noda Time

In my experience, it's relatively rare to have named command-line parameters which can also be specified without the names. 以我的经验,命名命令行参数相对很少见,也可以使用名称而指定它们。 So while arguably you could infer from the fact that there are five values that they're just the five values in the right order, it's more common to just require names for everything. 因此,尽管可以说,你可以从这样的事实推断,有五个价值,他们只是在正确的顺序五个值,这是比较常见的,只是需要的一切名称。

In your case, it looks like value1 is always required, so could be inferred to be the value for any unnamed argument... but I don't know if commandline supports that use case - you'd need to look into it. 在您的情况下,似乎总是需要value1 ,因此可以将其推断为任何未命名参数的值...但是我不知道命令行是否支持该用例-您需要调查一下。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM