如何在 C# 中返回数组文字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10921844/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 15:45:47  来源:igfitidea点击:

How to return an array literal in C#

c#

提问by sgarg

I'm trying the following code. The line with the error is pointed out.

我正在尝试以下代码。指出错误的行。

int[] myfunction()
{
    {
      //regular code
    }
    catch (Exception ex)
    {                    
       return {0,0,0}; //gives error
    }
}

How can I return an array literal like string literals?

如何返回像字符串文字这样的数组文字?

采纳答案by Blorgbeard is out

Return an array of intlike this:

返回一个这样的数组int

return new int [] { 0, 0, 0 };

You can also implicitly type the array- the compiler will infer it should be int[]because it contains only intvalues:

您还可以隐式键入数组- 编译器会推断它应该是,int[]因为它只包含int值:

return new [] { 0, 0, 0 };

回答by jb.

Blorgbeard is correct, but you also might think about using the new for .NET 4.0 Tuple class. I found it's easier to work with when you have a set number of items to return. As in if you always need to return 3 items in your array, a 3-int tuple makes it clear what it is.

Blorgbeard 是正确的,但您也可能会考虑使用新的 .NET 4.0 Tuple 类。我发现当你有一定数量的物品要返回时,它更容易处理。就像您总是需要在数组中返回 3 个项目一样,一个 3-int 元组可以清楚地表明它是什么。

return new Tuple<int,int,int>(0,0,0);

or simply

或者干脆

return Tuple.Create(0,0,0);

回答by anouar.bagari

if the array has a fixed size and you wante to return a new one filled with zeros

如果数组具有固定大小并且您想返回一个填充零的新数组

return new int[3];