반응형
선언한 행과 같은 행에서 C# 목록을 초기화하려면 어떻게 해야 합니까(IEnumerable String Collection 예)
테스트 코드를 쓰는 중인데 쓰고 싶지 않습니다.
List<string> nameslist = new List<string>();
nameslist.Add("one");
nameslist.Add("two");
nameslist.Add("three");
꼭 쓰고 싶다
List<string> nameslist = new List<string>({"one", "two", "three"});
단, {"1", "2", "3"은 ""이 아닙니다.IEnumerable String Collection"을 참조하십시오.IEnumberable String Collection을 사용하여 한 줄로 초기화하려면 어떻게 해야 합니까?
var list = new List<string> { "One", "Two", "Three" };
기본적으로 구문은 다음과 같습니다.
new List<Type> { Instance1, Instance2, Instance3 };
컴파일러에 의해 번역된 것은
List<string> list = new List<string>();
list.Add("One");
list.Add("Two");
list.Add("Three");
코드를 로 변경합니다.
List<string> nameslist = new List<string> {"one", "two", "three"};
또는
List<string> nameslist = new List<string>(new[] {"one", "two", "three"});
괄호를 놓치면 됩니다.
var nameslist = new List<string> { "one", "two", "three" };
목록을 POCO로 초기화하고 싶은 사용자를 위해 이 답변을 게시하고 검색에서 가장 먼저 나타나는 항목이지만 모든 답변은 문자열 유형의 목록에서만 나타납니다.
이 두 가지 방법은 설정자 할당을 통해 속성을 직접 설정하거나 매개 변수를 가져와 속성을 설정하는 생성자를 생성하여 훨씬 깔끔하게 설정하는 것입니다.
class MObject {
public int Code { get; set; }
public string Org { get; set; }
}
List<MObject> theList = new List<MObject> { new MObject{ PASCode = 111, Org="Oracle" }, new MObject{ PASCode = 444, Org="MS"} };
매개 변수화된 생성자에 의한 OR
class MObject {
public MObject(int code, string org)
{
Code = code;
Org = org;
}
public int Code { get; set; }
public string Org { get; set; }
}
List<MObject> theList = new List<MObject> {new MObject( 111, "Oracle" ), new MObject(222,"SAP")};
이게 한 가지 방법이에요.
List<int> list = new List<int>{ 1, 2, 3, 4, 5 };
이건 또 다른 방법이야.
List<int> list2 = new List<int>();
list2.Add(1);
list2.Add(2);
현도 마찬가지입니다.
예:
List<string> list3 = new List<string> { "Hello", "World" };
List<string> nameslist = new List<string> {"one", "two", "three"} ?
괄호를 삭제합니다.
List<string> nameslist = new List<string> {"one", "two", "three"};
사용하는 C#의 버전에 따라 버전 3.0 이후부터 사용할 수 있습니다.
List<string> nameslist = new List<string> { "one", "two", "three" };
이것은 int, long 및 string 값에 사용할 수 있다고 생각합니다.
List<int> list = new List<int>(new int[]{ 2, 3, 7 });
var animals = new List<string>() { "bird", "dog" };
언급URL : https://stackoverflow.com/questions/4438169/how-can-i-initialize-a-c-sharp-list-in-the-same-line-i-declare-it-ienumerable
반응형
'itsource' 카테고리의 다른 글
잠재적으로 위험한 요청입니다.클라이언트(*)에서 경로 값이 탐지되었습니다. (0) | 2023.04.22 |
---|---|
bash를 사용하여 각 행의 마지막 단어를 얻으려면 어떻게 해야 합니까? (0) | 2023.04.22 |
Mongoose Error [Mongoose Server Selection Error] : 52.6.250.237:27017에 대한 연결이 닫혔습니다. (0) | 2023.04.22 |
Swift를 사용하여 iOS에서 문자열을 MD5 해시로 변환하려면 어떻게 해야 합니까? (0) | 2023.04.22 |
WPF C# 패스: 패스 데이터가 있는 문자열에서 코드(XAML 이외)로 지오메트리로 이동하는 방법 (0) | 2023.04.22 |