문자열 값이 많은 문자열 목록(목록) 초기화 방법
(C# 이니셜라이저를 사용하여) 문자열 목록을 초기화하려면 어떻게 해야 합니까?아래 예시로 시도해 봤지만 잘 되지 않습니다.
List<string> optionList = new List<string>
{
"AdditionalCardPersonAddressType","AutomaticRaiseCreditLimit","CardDeliveryTimeWeekDay"
}();
제거만 하면 됩니다.()마지막에.
List<string> optionList = new List<string>
{ "AdditionalCardPersonAdressType", /* rest of elements */ };
List<string> mylist = new List<string>(new string[] { "element1", "element2", "element3" });
질문은 안 하셨지만 암호는
List<string> optionList = new List<string> { "string1", "string2", ..., "stringN"};
즉, 목록 뒤에 후행()이 없습니다.
var animals = new List<string> { "bird", "dog" };
List<string> animals= new List<string> { "bird", "dog" };
위의 두 가지 방법이 가장 빠른 방법입니다. https://www.dotnetperls.com/list를 참조하십시오.
당신의 기능은 정상입니다만, 당신이 그것을 넣었기 때문에 작동하지 않습니다.()마지막으로}를 이동하면()바로 옆 꼭대기로new List<string>()에러가 정지합니다.
아래 샘플:
List<string> optionList = new List<string>()
{
"AdditionalCardPersonAdressType","AutomaticRaiseCreditLimit","CardDeliveryTimeWeekDay"
};
C# 9.0 이후를 사용하고 있는 경우는, 새로운 기능을 사용할 수 있습니다.target-typed new expressions 링크
예:
List<string> stringList = new(){"item1","item2", "item3"} ;
선언과 함께 올바르게 초기화하는 방법은 다음과 같습니다.
List<string> optionList = new List<string>()
{
"AdditionalCardPersonAdressType","AutomaticRaiseCreditLimit","CardDeliveryTimeWeekDay"
};
이렇게 초기화하며 List를 사용할 수도 있습니다.[Add()] (더 다이내믹하게 하고 싶은 경우)
List<string> optionList = new List<string> {"AdditionalCardPersonAdressType"};
optionList.Add("AutomaticRaiseCreditLimit");
optionList.Add("CardDeliveryTimeWeekDay");
이 방법으로 IO에서 값을 가져올 경우 동적으로 할당된 목록에 값을 추가할 수 있습니다.
다음과 같이 둥근 괄호를 이동합니다.
var optionList = new List<string>(){"AdditionalCardPersonAdressType","AutomaticRaiseCreditLimit","CardDeliveryTimeWeekDay"};
리스트 이니셜라이저가 커스텀클래스에서도 정상적으로 동작하는 것은 정말 멋진 기능 중 하나입니다.즉 IEnumerable 인터페이스를 구현하고 Add라는 메서드를 사용하면 됩니다.
예를 들어 다음과 같은 커스텀클래스가 있는 경우:
class MyCustomCollection : System.Collections.IEnumerable
{
List<string> _items = new List<string>();
public void Add(string item)
{
_items.Add(item);
}
public IEnumerator GetEnumerator()
{
return _items.GetEnumerator();
}
}
이것은 동작합니다.
var myTestCollection = new MyCustomCollection()
{
"item1",
"item2"
}
아직 언급되지 않은 또 다른 무언가가 있을 수 있습니다.이미 트레일링()을 제거하려고 시도했지만 오류가 발생한 것으로 생각되므로 문제가 있을 수 있습니다.
먼저, 여기서 언급한 것처럼, 예에서는 후행()을 제거해야 합니다.
또, 리스트<>가 시스템에 있는 것도 주의해 주세요.컬렉션범용 네임스페이스
따라서 다음 두 가지 옵션 중 하나를 수행해야 합니다.[다음 #1이 더 선호됩니다]
(1) 코드 상단의 네임스페이스 사용을 시스템 사용으로 포함합니다.컬렉션범용
또는
(2) 선언문에 List에 완전 수식 경로를 기입한다.
System.Collections.포괄적인.optList=새로운 시스템을 나열합니다.컬렉션포괄적인.목록 {"Additional Card Person Address Type", Automatic Raise Credit Limit", Card Delivery Time요일" };
도움이 됐으면 좋겠다.
List를 올바르게 구현했지만 시스템을 포함하지 않은 경우 표시되는 오류 메시지.컬렉션일반 네임스페이스가 잘못되어 도움이 되지 않습니다.
컴파일러 오류 CS0308:일반적이지 않은 유형 목록은 형식 인수와 함께 사용할 수 없습니다."
PS - 시스템 사용을 지정하지 않으면 이 오류가 발생합니다.컬렉션포괄적인.컴파일러가 시스템 사용을 전제로 하고 있는 것을 나타냅니다.창문들.문서.목록.
콘텐츠 태그 C#을 보았습니다만, Java 를 사용할 수 있는 유저가 있는 경우는, 다음과 같습니다(같은 검색어는 같습니다.
List<String> mylist = Arrays.asList(new String[] {"element1", "element2", "element3" }.clone());
이렇게 하는 거야.
List <string> list1 = new List <string>();
잊지 말고 추가해 주세요
using System.Collections.Generic;
언급URL : https://stackoverflow.com/questions/3139118/how-to-initialize-a-list-of-strings-liststring-with-many-string-values
'source' 카테고리의 다른 글
| 한 필드의 날짜를 다른 필드의 시간과 결합하는 방법 - MS SQL Server (0) | 2023.04.19 |
|---|---|
| 'CELL TO THE LEFT'를 참조하기 위한 Excel 공식 (0) | 2023.04.19 |
| bash를 호출하고 새 셸 내에서 명령을 실행한 다음 사용자에게 제어권을 반환하려면 어떻게 해야 합니까? (0) | 2023.04.19 |
| "clone clone git@remote.git" 실행 시 사용자 이름과 비밀번호를 제공하려면 어떻게 해야 합니까? (0) | 2023.04.19 |
| 텍스트를 숫자로 변환하는 방법 (0) | 2023.04.19 |