简体   繁体   English

当元素不存在时,如何从数组中写入分配默认值?

[英]How can you write assign a default value from an array when the element does not exist?

This situation has always nagged me. 这种情况一直困扰着我。 Just as an example, suppose a console application expects filepath in as a command line argument. 仅作为示例,假设控制台应用程序期望将filepath作为命令行参数。

string first = args[0]; 

but if there are no arguments, then an error will occur. 但是如果没有参数,则会发生错误。 I suppose I could do something like the following: 我想我可以做以下事情:

string first = (args[0]!=null) ? args[0] : "c:\";

What I'm looking for is something a bit more elegant like: 我正在寻找的是更优雅的东西,例如:

string first = (MyTryParse(args[0],"c:\");

Which I could write as an extension, however that won't work because args[0] will throw an exception before the method can be called. 我可以将其编写为扩展,但是由于args [0]在调用该方法之前会引发异常,因此无法正常工作。

Also check, if args[0] is null: 还检查args[0]是否为null:

public string MyTryParse(string[] args, int index, string defaultVal)
{
    return index < args.Length ? (args[index] ?? defaultVal) : defaultVal
}
...
string first = MyTryParse(args, 0, "c:\");

Pass args instead of args[0] 传递args而不是args[0]

Try like this 这样尝试

public string MyTryParse(string[] args, string defaultVal) {
    return args.Length > 0 ? args[0] : defaultVal
}

Same approach but using extension method, 相同的方法,但是使用extension方法,

public static class Extensioin
{
    public static string MyTryParse(this string[] args, string defaultVal)
    {
        return args.Length > 0 ? args[0] : defaultVal;
    }
}

And using above method something like this, 然后使用上述方法,

string first = args.MyTryParse(@"c:\");

LINQ为此已经具有DefaultIfEmpty方法:

string first = args.DefaultIfEmpty("c:\\").First();

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

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