简体   繁体   English

在C#中,方括号在这方面意味着什么?

[英]What do square brackets mean in this context in C#?

What do the square brackets mean in a new expression in C# as follows: 方括号在C#中的新表达式中的含义如下:

public class MyClass
{
    public string Name { get; set; }
}

// ...

    var x = new MyClass[0]; // <-- what is this?

This is an array declaration The use of var just allows the compiler to decide on the type 这是一个数组声明。var的使用仅允许编译器确定类型

MyClass[] classArray = new MyClass[0];

The 0 inside the [] indicates that the number of array 'spaces' is 0 []内的0表示数组“空格”的数量为0

var classArray = new MyClass[5];

This will create an array of length 5, and the use of var will allow the compiler to decide on the type, which will be MyClass[] 这将创建一个长度为5的数组,并且使用var将允许编译器确定类型,即MyClass[]

You can access each place in the array I created above by using indexers, mentioned in another answer, similar to this, let's say MyClass has a property called name with public get and set accessors(stupid example I know) 您可以使用另一个答案中提到的索引器访问我在上面创建的数组中的每个位置,与此类似,假设MyClass具有一个名为name的属性,带有public get和set访问器(我知道这是愚蠢的示例)

classArray[1] = new MyClass();
classArray[1].Name = "Daniel's class";

This allows us to access the MyClass object held in the second array placement, this is indexing 这使我们可以访问第二个数组位置中保存的MyClass对象,这是索引

We can also create an array like this, let's say that the MyClass has a constructor that takes a string for the Name property 我们还可以创建一个像这样的数组,假设MyClass有一个构造函数,该构造函数接受Name属性的字符串

var x = new [] {
  new MyClass("Daniels"), 
  new MyClass("Yours"), 
  new MyClass("Ours")
};

Forgive me for my bad examples 原谅我的不好的例子

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

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