C#튜플(튜플)

PHPz
풀어 주다: 2017-03-12 15:47:29
원래의
1252명이 탐색했습니다.

1. 이전 버전 코드


 1 class Program 2 { 3     static void Main(string[] args) 4     { 5         var fullName = GetFullName(); 6  7         Console.WriteLine(fullName.Item1);// Item1,2,3不能忍,,, 8         Console.WriteLine(fullName.Item2); 9         Console.WriteLine(fullName.Item3);10     }11     static Tuple<string, string, string> GetFullName() => new Tuple<string, string, string>("first name", "blackheart", "last name");12 }
로그인 후 복사

일부 시나리오에서는 Microsoft가 .NET 4 일반 클래스에 Tuple을 도입하여 두 개 이상의 반환 값을 반환하는 방법이 필요합니다. 각 매개변수의 이름은 Item2,Item3 순서대로 지정됩니다. 이렇게 하면 문제가 부분적으로 해결되지만 강박 장애가 있는 프로그래머의 경우 Item1,2,3의 이름을 지정하는 것은 참을 수 없습니다. ,,,그래서 C#7에서는 이 문제를 해결하기 위해 새로운 일반 유형 ValueTuplel(System.ValueTuple)이 도입되었습니다. nuget(http://www.php.cn/)을 통해 현재 프로젝트에 도입할 수 있습니다.

2. ValueTuple

말도 안 돼요. 코드를 보세요.


 1 class Program 2 { 3     static void Main(string[] args) 4     { 5         var fullName = GetFullName(); 6  7         Console.WriteLine(fullName.First);  // 终于可以不是Item1,2,3了,,, 8         Console.WriteLine(fullName.Middle); 9         Console.WriteLine(fullName.Last);10     }11 12     static (string First, string Middle, string Last) GetFullName() => ("first name", "blackheart", "last name");13 }
로그인 후 복사
차이점이 보이시나요? 마침내 "Item1,2,3"을 좀 더 직관적인 것으로 바꿀 수 있습니다. 하지만 위에서 언급한 System.ValueTuple을 사용하지 않은 것 같습니다. 컴파일된 어셈블리를 열고 살펴보겠습니다.


 1 internal class Program 2 { 3     private static void Main(string[] args) 4     { 5         ValueTuple<string, string, string> fullName = Program.GetFullName(); 6         Console.WriteLine(fullName.Item1); // 原来你还是Item1,2,3,,,FUCK!!! 7         Console.WriteLine(fullName.Item2); 8         Console.WriteLine(fullName.Item3); 9     }10 11     [TupleElementNames(new string[]12     {13             "First",14             "Middle",15             "Last"16     })]17     private static ValueTuple<string, string, string> GetFullName()18     {19         return new ValueTuple<string, string, string>("first name", "blackheart", "last name");20     }21 }
로그인 후 복사
사용하지 않으면 알 수 없습니다. 보지 마세요. 컴파일 후에

fullName.First;fullName.Item1인 것을 알고는 정말 안타까웠습니다. . .

의 차이점은

GetFullName 메서드에서 컴파일러가 단순화된 구문을 ValueTuple<string, string, 으로 변환한다는 것입니다. string>을 추가하고 새 속성(TupleElementNamesAttribute)을 추가한 다음 매우 직관적이고 친숙한 "First", "Middle", "Last" "메타데이터로 저장"을 정의했습니다. (로컬에서만 사용하는 경우 해당 메타데이터는 추가되지 않습니다). TupleElementNamesAttribute는 ValueTuple과 동일하며 System.ValueTuple의 별도 dll에 위치합니다.

3. 예시


 1 class Program 2 { 3     static void Main(string[] args) 4     { 5         var range = (first: 1, end: 10); 6         //也可以这样写,效果是一样的,编译后都是没有了first,end的痕迹,,,first和end只是语法层面的障眼法 7         //(int first, int last) range = (1, 10); 8         Console.WriteLine(range.first); 9         Console.WriteLine(range.end);10 11         //可以使用var,这种无显示声明一个变量的方式会编译出多余的代码,慎用,不知是不是还未优化好。12         (var begin, var end) = (DateTime.Parse("2017-1-1"), DateTime.Parse("2017-12-31"));13         Console.WriteLine(begin);14         Console.WriteLine(end);15 16         //begin,end可以被覆盖重命名为startDate和endDate,但是会有一个编译警告,提示名字被忽略掉了。17         //warning CS8123: The tuple element name 'begin' is ignored because a different name is specified by the target type '(DateTime startDate, DateTime endDate)'18         //warning CS8123: The tuple element name 'end' is ignored because a different name is specified by the target type '(DateTime startDate, DateTime endDate)‘19         (DateTime startDate, DateTime endDate) timeSpan = (begin: DateTime.Parse("2017-1-1"), end: DateTime.Parse("2017-12-31"));20         Console.WriteLine(timeSpan.startDate);21         Console.WriteLine(timeSpan.endDate);22     }23 }
로그인 후 복사
컴파일된 코드를 보세요:

🎜>

 1 private static void Main(string[] args) 2 { 3     ValueTuple<int, int> range = new ValueTuple<int, int>(1, 10); 4     Console.WriteLine(range.Item1); 5     Console.WriteLine(range.Item2); 6     ValueTuple<DateTime, DateTime> expr_3C = new ValueTuple<DateTime, DateTime>(DateTime.Parse("2017-1-1"), DateTime.Parse("2017-12-31"));
 7     DateTime item = expr_3C.Item1;
 8     DateTime item2 = expr_3C.Item2;
 9     DateTime begin = item;
10     DateTime end = item2;11     Console.WriteLine(begin);12     Console.WriteLine(end);13     ValueTuple<DateTime, DateTime> timeSpan = new ValueTuple<DateTime, DateTime>(DateTime.Parse("2017-1-1"), DateTime.Parse("2017-12-31"));14     Console.WriteLine(timeSpan.Item1);15     Console.WriteLine(timeSpan.Item2);16 }
로그인 후 복사

참고 (

varbegin, varend) = (DateTime.Parse("2017-1- 1 "), DateTime.Parse("2017-12-31")); 이 줄은 저렴한 결과는 매우 나빠 보입니다(위 6-10행의 빨간색 부분). 이는 컴파일 최적화가 충분하지 않은 문제일 수 있습니다(릴리스 컴파일의 경우에도 마찬가지). 4.

요약

새로운 구문 형식은 실제로 훨씬 더 직관적이고 친숙하지만 본질은 여전히 ​​제네릭 유형의 도움으로 구현되며 컴파일러는 다음과 같습니다. 새로운 구문 형식을 지원하는 데도 필요합니다.

본질이 무엇인지 이해한 후, 앞으로도 환경이 허락한다면 과감하게 사용해보세요(

ValueTuple 유형이 나타날 수 있는 곳은 (첫 번째, 마지막) 이 새로운 문법적 형태는 )일 수 있습니다.

위 내용은 C#튜플(튜플)의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
c#
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!