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# 聲明類的時候初始化類