所有可能的数组初始化语法

发布于 2024-11-01 18:35:56 字数 28 浏览 6 评论 0原文

C# 可以使用的所有数组初始化语法有哪些?

What are all the array initialization syntaxes that are possible with C#?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(21

盗琴音 2024-11-08 18:35:56

这些是简单数组的当前声明和初始化方法。

string[] array = new string[2]; // creates array of length 2, default values
string[] array = new string[] { "A", "B" }; // creates populated array of length 2
string[] array = { "A" , "B" }; // creates populated array of length 2
string[] array = new[] { "A", "B" }; // creates populated array of length 2
string[] array = ["A", "B"]; // creates populated array of length 2

请注意,还存在其他获取数组的技术,例如 IEnumerable 上的 Linq ToArray() 扩展。

另请注意,在上面的声明中,前两个可以将左侧的 string[] 替换为 var (C# 3+),因为右侧的信息就足够了推断正确的类型。第三行必须按照显示的方式编写,因为单独的数组初始化语法不足以满足编译器的要求。第四种也可以使用推理。第五行在 C# 12 中作为集合表达式引入,其中无法推断目标类型。它还可用于跨度和列表。如果您喜欢整个简洁性,上面的内容可以写成

var array = new string[2]; // creates array of length 2, default values
var array = new string[] { "A", "B" }; // creates populated array of length 2
string[] array = { "A" , "B" }; // creates populated array of length 2
var array = new[] { "A", "B" }; // created populated array of length 2
string[] array = ["A", "B"]; // creates populated array of length 2

These are the current declaration and initialization methods for a simple array.

string[] array = new string[2]; // creates array of length 2, default values
string[] array = new string[] { "A", "B" }; // creates populated array of length 2
string[] array = { "A" , "B" }; // creates populated array of length 2
string[] array = new[] { "A", "B" }; // creates populated array of length 2
string[] array = ["A", "B"]; // creates populated array of length 2

Note that other techniques of obtaining arrays exist, such as the Linq ToArray() extensions on IEnumerable<T>.

Also note that in the declarations above, the first two could replace the string[] on the left with var (C# 3+), as the information on the right is enough to infer the proper type. The third line must be written as displayed, as array initialization syntax alone is not enough to satisfy the compiler's demands. The fourth could also use inference. The fifth line was introduced in C# 12 as collection expressions where the target type cannot be inferenced. It can also be used for spans and lists. If you're into the whole brevity thing, the above could be written as

var array = new string[2]; // creates array of length 2, default values
var array = new string[] { "A", "B" }; // creates populated array of length 2
string[] array = { "A" , "B" }; // creates populated array of length 2
var array = new[] { "A", "B" }; // created populated array of length 2
string[] array = ["A", "B"]; // creates populated array of length 2
怀里藏娇 2024-11-08 18:35:56

C# 中作为表达式的数组创建语法是:

new int[3]
new int[3] { 10, 20, 30 }
new int[] { 10, 20, 30 }
new[] { 10, 20, 30 }

在第一个语法中,大小可以是任何非负整数值,并且数组元素被初始化为默认值。

在第二个中,大小必须是常量,并且给定的元素数量必须匹配。必须存在从给定元素到给定数组元素类型的隐式转换。

在第三种中,元素必须可隐式转换为元素类型,并且大小由给定元素的数量确定。

在第四个中,通过计算所有具有类型的给定元素的最佳类型(如果有)来推断数组元素的类型。所有元素都必须可隐式转换为该类型。大小由给定元素的数量确定。此语法是在 C# 3.0 中引入的。

还有一种只能在声明中使用的语法:

int[] x = { 10, 20, 30 };

元素必须可以隐式转换为元素类型。大小由给定元素的数量确定。

没有一本完整的指南

我建议您参考 C# 4.0 规范,第 7.6.10.4 节“数组创建表达式”。

The array creation syntaxes in C# that are expressions are:

new int[3]
new int[3] { 10, 20, 30 }
new int[] { 10, 20, 30 }
new[] { 10, 20, 30 }

In the first one, the size may be any non-negative integral value and the array elements are initialized to the default values.

In the second one, the size must be a constant and the number of elements given must match. There must be an implicit conversion from the given elements to the given array element type.

In the third one, the elements must be implicitly convertible to the element type, and the size is determined from the number of elements given.

In the fourth one the type of the array element is inferred by computing the best type, if there is one, of all the given elements that have types. All the elements must be implicitly convertible to that type. The size is determined from the number of elements given. This syntax was introduced in C# 3.0.

There is also a syntax which may only be used in a declaration:

int[] x = { 10, 20, 30 };

The elements must be implicitly convertible to the element type. The size is determined from the number of elements given.

there isn't an all-in-one guide

I refer you to C# 4.0 specification, section 7.6.10.4 "Array Creation Expressions".

迷你仙 2024-11-08 18:35:56

非空数组

  • var data0 = new int[3]

  • var data1 =新 int[3] { 1, 2, 3 }

  • var data2 = 新int[] { 1, 2, 3 }

  • var data3 = new[ ] { 1, 2, 3 }

  • var data4 = { 1, 2, 3 } 不可编译。请改用 int[] data5 = { 1, 2, 3 }

空数组

  • var data6 = new int[0]
  • var data7 = new int[] { }
  • var data8 = new [] { }int[] data9 = new [] { } 不可编译。

  • var data10 = { } 不可编译。请改用 int[] data11 = { }

作为方法的参数

只有可以使用 var 关键字指定的表达式才能作为参数传递。

  • Foo(new int[2])
  • Foo(new int[2] { 1, 2 })
  • Foo(new int[] { 1, 2 })
  • Foo(new[] { 1, 2 })
  • Foo({ 1, 2 }) 不可编译
  • Foo(new int[0] )
  • Foo(new int[] { })
  • Foo({}) 不可编译

Non-empty arrays

  • var data0 = new int[3]

  • var data1 = new int[3] { 1, 2, 3 }

  • var data2 = new int[] { 1, 2, 3 }

  • var data3 = new[] { 1, 2, 3 }

  • var data4 = { 1, 2, 3 } is not compilable. Use int[] data5 = { 1, 2, 3 } instead.

Empty arrays

  • var data6 = new int[0]
  • var data7 = new int[] { }
  • var data8 = new [] { } and int[] data9 = new [] { } are not compilable.

  • var data10 = { } is not compilable. Use int[] data11 = { } instead.

As an argument of a method

Only expressions that can be assigned with the var keyword can be passed as arguments.

  • Foo(new int[2])
  • Foo(new int[2] { 1, 2 })
  • Foo(new int[] { 1, 2 })
  • Foo(new[] { 1, 2 })
  • Foo({ 1, 2 }) is not compilable
  • Foo(new int[0])
  • Foo(new int[] { })
  • Foo({}) is not compilable
望喜 2024-11-08 18:35:56
Enumerable.Repeat(String.Empty, count).ToArray()

将创建重复“count”次的空字符串数组。如果您想使用相同但特殊的默认元素值初始化数组。小心引用类型,所有元素都将引用同一个对象。

Enumerable.Repeat(String.Empty, count).ToArray()

Will create array of empty strings repeated 'count' times. In case you want to initialize array with same yet special default element value. Careful with reference types, all elements will refer same object.

韬韬不绝 2024-11-08 18:35:56

如果您想初始化预先初始化的相等(非 nulldefault 之外的元素)元素的固定数组,请使用以下内容:

var array = Enumerable.Repeat(string.Empty, 37).ToArray();

另请参加 讨论。

In case you want to initialize a fixed array of pre-initialized equal (non-null or other than default) elements, use this:

var array = Enumerable.Repeat(string.Empty, 37).ToArray();

Also please take part in this discussion.

九命猫 2024-11-08 18:35:56
var contacts = new[]
{
    new 
    {
        Name = " Eugene Zabokritski",
        PhoneNumbers = new[] { "206-555-0108", "425-555-0001" }
    },
    new 
    {
        Name = " Hanying Feng",
        PhoneNumbers = new[] { "650-555-0199" }
    }
};
var contacts = new[]
{
    new 
    {
        Name = " Eugene Zabokritski",
        PhoneNumbers = new[] { "206-555-0108", "425-555-0001" }
    },
    new 
    {
        Name = " Hanying Feng",
        PhoneNumbers = new[] { "650-555-0199" }
    }
};
你的心境我的脸 2024-11-08 18:35:56

创建自定义类数组的示例

下面是类定义。

public class DummyUser
{
    public string email { get; set; }
    public string language { get; set; }
}

这是初始化数组的方法:

private DummyUser[] arrDummyUser = new DummyUser[]
{
    new DummyUser{
       email = "[email protected]",
       language = "English"
    },
    new DummyUser{
       email = "[email protected]",
       language = "Spanish"
    }
};

Example to create an array of a custom class

Below is the class definition.

public class DummyUser
{
    public string email { get; set; }
    public string language { get; set; }
}

This is how you can initialize the array:

private DummyUser[] arrDummyUser = new DummyUser[]
{
    new DummyUser{
       email = "[email protected]",
       language = "English"
    },
    new DummyUser{
       email = "[email protected]",
       language = "Spanish"
    }
};
旧瑾黎汐 2024-11-08 18:35:56

请注意

以下数组:

string[] array = new string[2];
string[] array2 = new string[] { "A", "B" };
string[] array3 = { "A" , "B" };
string[] array4 = new[] { "A", "B" };

编译为:

string[] array = new string[2];
string[] array2 = new string[] { "A", "B" };
string[] array3 = new string[] { "A", "B" };
string[] array4 = new string[] { "A", "B" };

Just a note

The following arrays:

string[] array = new string[2];
string[] array2 = new string[] { "A", "B" };
string[] array3 = { "A" , "B" };
string[] array4 = new[] { "A", "B" };

Will be compiled to:

string[] array = new string[2];
string[] array2 = new string[] { "A", "B" };
string[] array3 = new string[] { "A", "B" };
string[] array4 = new string[] { "A", "B" };
一城柳絮吹成雪 2024-11-08 18:35:56

不使用LINQ重复:

float[] floats = System.Array.ConvertAll(new float[16], v => 1.0f);

Repeat without LINQ:

float[] floats = System.Array.ConvertAll(new float[16], v => 1.0f);
柠檬心 2024-11-08 18:35:56
int[] array = new int[4]; 
array[0] = 10;
array[1] = 20;
array[2] = 30;

string[] week = new string[] {"Sunday","Monday","Tuesday"};

或和

string[] array = { "Sunday" , "Monday" };

多维数组中的

    Dim i, j As Integer
    Dim strArr(1, 2) As String

    strArr(0, 0) = "First (0,0)"
    strArr(0, 1) = "Second (0,1)"

    strArr(1, 0) = "Third (1,0)"
    strArr(1, 1) = "Fourth (1,1)"
int[] array = new int[4]; 
array[0] = 10;
array[1] = 20;
array[2] = 30;

or

string[] week = new string[] {"Sunday","Monday","Tuesday"};

or

string[] array = { "Sunday" , "Monday" };

and in multi dimensional array

    Dim i, j As Integer
    Dim strArr(1, 2) As String

    strArr(0, 0) = "First (0,0)"
    strArr(0, 1) = "Second (0,1)"

    strArr(1, 0) = "Third (1,0)"
    strArr(1, 1) = "Fourth (1,1)"
我家小可爱 2024-11-08 18:35:56
For Class initialization:
var page1 = new Class1();
var page2 = new Class2();
var pages = new UIViewController[] { page1, page2 };
For Class initialization:
var page1 = new Class1();
var page2 = new Class2();
var pages = new UIViewController[] { page1, page2 };
何时共饮酒 2024-11-08 18:35:56

在 C# 12 中,您将能够创建如下数组: int[] Positions = [1, 2, 3];

真的很棒!

In C# 12, you will able to create an array like this : int[] positions = [1, 2, 3];

Really great !

逆流 2024-11-08 18:35:56

创建和初始化对象数组的另一种方法。这与 @Amol 上面发布的示例类似,只不过这个示例使用了构造函数。一丝多态性洒入其中,我无法抗拒。

IUser[] userArray = new IUser[]
{
    new DummyUser("[email protected]", "Gibberish"),
    new SmartyUser("[email protected]", "Italian", "Engineer")
};

上下文类:

interface IUser
{
    string EMail { get; }       // immutable, so get only an no set
    string Language { get; }
}

public class DummyUser : IUser
{
    public DummyUser(string email, string language)
    {
        m_email = email;
        m_language = language;
    }

    private string m_email;
    public string EMail
    {
        get { return m_email; }
    }

    private string m_language;
    public string Language
    {
        get { return m_language; }
    }
}

public class SmartyUser : IUser
{
    public SmartyUser(string email, string language, string occupation)
    {
        m_email = email;
        m_language = language;
        m_occupation = occupation;
    }

    private string m_email;
    public string EMail
    {
        get { return m_email; }
    }

    private string m_language;
    public string Language
    {
        get { return m_language; }
    }

    private string m_occupation;
}

Another way of creating and initializing an array of objects. This is similar to the example which @Amol has posted above, except this one uses constructors. A dash of polymorphism sprinkled in, I couldn't resist.

IUser[] userArray = new IUser[]
{
    new DummyUser("[email protected]", "Gibberish"),
    new SmartyUser("[email protected]", "Italian", "Engineer")
};

Classes for context:

interface IUser
{
    string EMail { get; }       // immutable, so get only an no set
    string Language { get; }
}

public class DummyUser : IUser
{
    public DummyUser(string email, string language)
    {
        m_email = email;
        m_language = language;
    }

    private string m_email;
    public string EMail
    {
        get { return m_email; }
    }

    private string m_language;
    public string Language
    {
        get { return m_language; }
    }
}

public class SmartyUser : IUser
{
    public SmartyUser(string email, string language, string occupation)
    {
        m_email = email;
        m_language = language;
        m_occupation = occupation;
    }

    private string m_email;
    public string EMail
    {
        get { return m_email; }
    }

    private string m_language;
    public string Language
    {
        get { return m_language; }
    }

    private string m_occupation;
}
无边思念无边月 2024-11-08 18:35:56

您好,只是添加另一种方式:
从这个页面:
https://learn. microsoft.com/it-it/dotnet/api/system.linq.enumerable.range?view=netcore-3.1

如果您想生成指定范围内的整数序列,您可以使用此表单范围 strat 0 到 9:

using System.Linq
.....
public int[] arrayName = Enumerable.Range(0, 9).ToArray();

hi just to add another way:
from this page :
https://learn.microsoft.com/it-it/dotnet/api/system.linq.enumerable.range?view=netcore-3.1

you can use this form If you want to Generates a sequence of integral numbers within a specified range strat 0 to 9:

using System.Linq
.....
public int[] arrayName = Enumerable.Range(0, 9).ToArray();
生活了然无味 2024-11-08 18:35:56

从 C# 12 开始,您现在还可以使用 集合表达式。请注意扩展运算符 ..,它将采用 IEnumerable 并将其项目展平到集合表达式中。一些示例:

仅一个元素

int[] array = [1];

100 个元素,其中每个元素代表其索引

int[] array = [.. Enumerable.Range(0, 100)];

由 12 个元素组成的数组,其中第一个和最后一个值为 1,其余为 0

int[] array = [1, .. Enumerable.Repeat(0, 10), 1];

请注意,集合表达式不仅限于数组,还可以用于构造许多不同类型的集合,包括通常不可构造的集合(例如接口和 Span):

List<int> list = [1];
HashSet<int> set = [1];
IReadOnlyCollection<int> readOnlyCollection = [1];
IEnumerable<int> enumerable = [1];
Span<int> span = [1];

As of C# 12, you can now also initialize arrays with collection expressions. Note the spread operator .., which will take an IEnumerable and flatten its items inside a collection expression. Some examples:

Just a single element

int[] array = [1];

100 elements where each element represents its index

int[] array = [.. Enumerable.Range(0, 100)];

An array of 12 elements where the first and last values are 1 and the rest are 0

int[] array = [1, .. Enumerable.Repeat(0, 10), 1];

Note that collection expressions are not exclusive to arrays and can be used to construct many different types of collections, including those not typically constructable (like interfaces and Span):

List<int> list = [1];
HashSet<int> set = [1];
IReadOnlyCollection<int> readOnlyCollection = [1];
IEnumerable<int> enumerable = [1];
Span<int> span = [1];
孤者何惧 2024-11-08 18:35:56

对于下面的类:

public class Page
{

    private string data;

    public Page()
    {
    }

    public Page(string data)
    {
        this.Data = data;
    }

    public string Data
    {
        get
        {
            return this.data;
        }
        set
        {
            this.data = value;
        }
    }
}

您可以如下初始化上述对象的数组。

Pages = new Page[] { new Page("a string") };

希望这有帮助。

For the class below:

public class Page
{

    private string data;

    public Page()
    {
    }

    public Page(string data)
    {
        this.Data = data;
    }

    public string Data
    {
        get
        {
            return this.data;
        }
        set
        {
            this.data = value;
        }
    }
}

you can initialize the array of above object as below.

Pages = new Page[] { new Page("a string") };

Hope this helps.

盗梦空间 2024-11-08 18:35:56

您还可以创建动态数组,即您可以在创建数组之前首先询问用户数组的大小。

Console.Write("Enter size of array");
int n = Convert.ToInt16(Console.ReadLine());

int[] dynamicSizedArray= new int[n]; // Here we have created an array of size n
Console.WriteLine("Input Elements");
for(int i=0;i<n;i++)
{
     dynamicSizedArray[i] = Convert.ToInt32(Console.ReadLine());
}

Console.WriteLine("Elements of array are :");
foreach (int i in dynamicSizedArray)
{
    Console.WriteLine(i);
}
Console.ReadKey();

You can also create dynamic arrays i.e. you can first ask the size of the array from the user before creating it.

Console.Write("Enter size of array");
int n = Convert.ToInt16(Console.ReadLine());

int[] dynamicSizedArray= new int[n]; // Here we have created an array of size n
Console.WriteLine("Input Elements");
for(int i=0;i<n;i++)
{
     dynamicSizedArray[i] = Convert.ToInt32(Console.ReadLine());
}

Console.WriteLine("Elements of array are :");
foreach (int i in dynamicSizedArray)
{
    Console.WriteLine(i);
}
Console.ReadKey();
幸福%小乖 2024-11-08 18:35:56

带表达式的简单解决方案。请注意,使用 NewArrayInit 只能创建一维数组。

NewArrayExpression expr = Expression.NewArrayInit(typeof(int), new[] { Expression.Constant(2), Expression.Constant(3) });
int[] array = Expression.Lambda<Func<int[]>>(expr).Compile()(); // compile and call callback

Trivial solution with expressions. Note that with NewArrayInit you can create just one-dimensional array.

NewArrayExpression expr = Expression.NewArrayInit(typeof(int), new[] { Expression.Constant(2), Expression.Constant(3) });
int[] array = Expression.Lambda<Func<int[]>>(expr).Compile()(); // compile and call callback
叹沉浮 2024-11-08 18:35:56

要初始化一个空数组,它应该是 dotnet 5.0

对于字符串

var items = Array.Empty<string>();

对于数字

var items = Array.Empty<int>();

To initialize an empty array, it should be Array.Empty<T>() in dotnet 5.0

For string

var items = Array.Empty<string>();

For number

var items = Array.Empty<int>();
不再让梦枯萎 2024-11-08 18:35:56

另一种方法是调用静态函数(对于静态对象)或实例对象的任何函数。这可用于成员初始化。

现在我还没有测试所有这些,所以我将把我测试过的内容(静态成员和静态函数)放在

Class x {
    private static Option[] options = GetOptionList();
    private static Option[] GetOptionList() {

        return (someSourceOfData).Select(dataitem => new Option()
                 {field=dataitem.value,field2=dataitem.othervalue});
    }
}

我想知道的是是否有一种方法可以绕过函数声明。我知道在这个例子中它可以直接使用,但假设该函数稍微复杂一点并且不能简化为单个表达式。

我想象类似下面的东西(但它不起作用)

Class x {
    private static Option[] options = () => {
        Lots of prep stuff here that means we can not just use the next line
        return (someSourceOfData).Select(dataitem => new Option()
                 {field=dataitem.value,field2=dataitem.othervalue});
    }
}

基本上是一种仅声明填充变量范围的函数的方法。
如果有人能告诉我如何做到这一点,我会很高兴。

Another way is by calling a static function (for a static object) or any function for instance objects. This can be used for member initialisation.

Now I've not tested all of this so I'll put what I've tested (static member and static function)

Class x {
    private static Option[] options = GetOptionList();
    private static Option[] GetOptionList() {

        return (someSourceOfData).Select(dataitem => new Option()
                 {field=dataitem.value,field2=dataitem.othervalue});
    }
}

What I'd love to know is if there is a way to bypass the function declaration. I know in this example it could be used directly, but assume the function is a little more complex and can't be reduced to a single expression.

I imagine something like the following (but it doesn't work)

Class x {
    private static Option[] options = () => {
        Lots of prep stuff here that means we can not just use the next line
        return (someSourceOfData).Select(dataitem => new Option()
                 {field=dataitem.value,field2=dataitem.othervalue});
    }
}

Basically a way of just declaring the function for the scope of filling the variable.
I'd love it if someone can show me how to do that.

骷髅 2024-11-08 18:35:56

对于C#中的多维数组声明&赋值。

public class Program
{
    static void Main()
    {
        char[][] charArr = new char[][] { new char[] { 'a', 'b' }, new char[] { 'c', 'd' } };

        int[][] intArr = new int[][] { new int[] { 1, 2 }, new int[] { 3, 4 } };
    }

}

For multi-dimensional array in C# declaration & assign values.

public class Program
{
    static void Main()
    {
        char[][] charArr = new char[][] { new char[] { 'a', 'b' }, new char[] { 'c', 'd' } };

        int[][] intArr = new int[][] { new int[] { 1, 2 }, new int[] { 3, 4 } };
    }

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文