c# 声明类的时候初始化类
The task is to create/declare a list with an initializer list in C#.
任务是在C#中使用初始化列表创建/声明一个列表 。
C#清单 (C# List)
A list is used to represent the list of the objects, it is represented as List<T>, where T is the type of the list objects/elements.
列表用于表示对象的列表,它表示为List <T> ,其中T是列表对象/元素的类型。
A list is a class which comes under System.Collections.Generic package, so we have to include it first.
列表是System.Collections.Generic包下的一个类,因此我们必须首先包含它。
具有初始化的列表声明 (List declaration with initialization)
To declare and initialize a list with the elements/objects, we use the following syntax,
要使用元素/对象声明和初始化列表 ,我们使用以下语法,
List<T> list_name= new List<T> {list_of_objects/elements};
Here, T is the type and list_name is the name of the list.
在这里, T是类型, list_name是列表的名称。
Examples:
例子:
//an integer list
List<int> int_list = new List<int> { 10, 20, 30, 40, 50 };
//a string list
List<string> str_list = new List<string>{
"Manju", "Amit", "Abhi", "Radib", "Prem"
};
Here, int_list is a list of integer elements and str_list is a list of string elements.
在这里, int_list是整数元素的列表, str_list是字符串元素的列表。
C#程序使用初始化来创建/声明列表 (C# program to create/declare a list with initialization )
using System;
using System.Text;
using System.Collections.Generic;
namespace Test
{
class Program
{
static void Main(string[] args)
{
//an integer list
List<int> int_list = new List<int> { 10, 20, 30, 40, 50 };
//a string list
List<string> str_list = new List<string>{
"Manju", "Amit", "Abhi", "Radib", "Prem"
};
//printing list elements
Console.WriteLine("int_list elements...");
foreach (int item in int_list)
{
Console.Write(item + " ");
}
Console.WriteLine();
Console.WriteLine("str_list elements...");
foreach (string item in str_list)
{
Console.Write(item + " ");
}
Console.WriteLine();
//hit ENTER to exit
Console.ReadLine();
}
}
}
Output
输出量
int_list elements...
10 20 30 40 50
str_list elements...
Manju Amit Abhi Radib Prem
翻译自: https://www.includehelp.com/dot-net/list-declaration-with-initialization-in-c-sharp.aspx
c# 声明类的时候初始化类