C # 버전 8부터는 예와 같이 새로운 인덱싱 방법이 있습니다 .
void Main()
{
Index idx = ^5; // counted from last to first element
var sentence = new string[]
{
"The", "quick", "brown", "fox", // position 0 ... 3
"jumped", "over", "the", "lazy", "dog" // position 4 ... 8
};
var lstSentence = sentence.ToList(); // applicable to list as well
Console.WriteLine(sentence[idx]);
Console.WriteLine(lstSentence[idx]);
}
반환합니다 jumped
.
여태까지는 그런대로 잘됐다. 그러나 어떻게 ^5
효율적 으로 나타내는 절대 위치를 얻을 수 있습니까?
.NET이 내부적으로 Index (이 예제에 추가 한)를 사용하는 것을 보았고 값 속성이 있습니다.
의 위치를 sentence[^5]
어떻게 얻을 수 있습니까? 같은 것
var absPos = sentence[^5].Index.Value; // get absolute position (which is = 4)
(그러나 불행히도 이것은 존재하지 않는 것 같습니다)
수식 (요소 수-오른쪽에서 위치)이 있다는 것을 알고 있지만 컴파일러 / .net은 이것을 계산하고 아마도 어딘가에 저장합니다.
업데이트 : idx.Value는 해결책이 아니며 상대 값 5를 .IsFromEnd와 함께 저장합니다. 하지만 sentence[^5].Index.Value
내가 알고 싶었던 것처럼 직접 액세스 할 수는 없습니다 .
참고 : 이는 RudimentaryMultiValuedDictionary 예제를Dictionary
살펴보면 에도 유용 합니다. 필요한 추가 인덱서를 추가하려는 경우 . 이 목적에 필요한은 정수 값 (절대 위치)에서만 작동합니다.public List<TValue> this[Index idx]
internalDictionary.ElementAtOrDefault(i)
디 컴파일러를 사용하여 예제에 대해 생성 된 코드를 확인하는 경우 다음과 같습니다.
private static void Main()
{
Index index = new Index(5, true);
string[] strArray = new string[] { "The", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog" };
Console.WriteLine(strArray[index.GetOffset((int)strArray.Length)]);
}
보시다시피 index.GetOffset((int)strArray1.Length)
오프셋을 계산하는 데 사용 됩니다. 같은 방식으로 수행하는 것 외에는 직접 수행 할 수있는 방법이 없습니다. 사용할 수있는 다른 언어 구조는 없습니다.
( 이미이므로 strArray1.Length
속성을 캐스트하는 이유를 잘 모르겠습니다 .)int
int
또한 다음과 같은 코드를 사용하여 인덱스를 인라인으로 넣는 경우에도 유의하십시오.
var sentence = new string[]
{
"The", "quick", "brown", "fox",
"jumped", "over", "the", "lazy", "dog"
};
Console.WriteLine(sentence[^5]);
다음과 같이 컴파일됩니다.
string[] strArray = new string[] { "The", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog" };
Console.WriteLine(strArray[(int)strArray.Length - 5]);
Index
객체 의 사용을 완전히 최적화 했습니다.
아래 주석에서 언급했듯이 IList
. 그런 다음 , 배열 IList
등과 같은 구현하는 모든 항목에서 작동 합니다.List<T>
ImmutableSortedSet<T>
예를 들면 :
public static class IndexExt
{
public static int AbsIndexFor(this IList self, Index index)
{
return index.GetOffset(self.Count);
}
}
그런 다음 다음을 수행 할 수 있습니다.
var array = new string[]
{
"The", "quick", "brown", "fox",
"jumped", "over", "the", "lazy", "dog"
};
Console.WriteLine(array.AbsIndexFor(^5));
var list = new List<string>
{
"The", "quick", "brown", "fox",
"jumped", "over", "the", "lazy", "dog"
};
Console.WriteLine(list.AbsIndexFor(^5));
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다