[C#3] - 객체 및 컬렉션 초기화기

11406 단어

1. 객체 초기화기


먼저 클래스 Person을 선언합니다.
public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

초기화하고 호출하기
static void Main()
{
    Person person = new Person { Name = " ", Age = 22 };
    Console.WriteLine(" :{0}",person.Name);
    Console.WriteLine(" :{0}", person.Age.ToString());
}

이것은 컴파일러의 작은 방법입니다. IL 코드는 일반적인 초기화 작업과 효과가 완전히 같다는 것을 보여 줍니다.안에 나타나는 것은 반드시 공유된 구성원, 필드 또는 속성이어야 한다.대상 초기화기를 지원할 수 있는 유형은 하나의 조건을 충족시켜야 한다. 공유된 무참한 구조 함수가 있어야 한다.

2. 집합 초기화기

static void Main()
{
    List personList = new List {
        new Person { Name = " ", Age = 22 },
        new Person { Name = " ", Age = 21 } };
    for (int i = 0; i < personList.Count; i++)
    {
        Console.Write(personList[i].Name+"--");
        Console.WriteLine(personList[i].Age);
        Console.WriteLine("=====================");
    }
}

IL 코드를 볼 필요가 있습니다.
 1 .method private hidebysig static void  Main() cil managed
 2 {
 3   .entrypoint
 4   //         166 (0xa6)
 5   .maxstack  3
 6   .locals init ([0] class [mscorlib]System.Collections.Generic.List`1<class ConsoleApplication1.Person> personList,
 7            [1] int32 i,
 8            [2] class [mscorlib]System.Collections.Generic.List`1<class ConsoleApplication1.Person> '<>g__initLocal0',
 9            [3] class ConsoleApplication1.Person '<>g__initLocal1',
10            [4] class ConsoleApplication1.Person '<>g__initLocal2',
11            [5] bool CS$4$0000)
12   IL_0000:  nop
13   IL_0001:  newobj     instance void class [mscorlib]
14                System.Collections.Generic.List`1<class ConsoleApplication1.Person>::.ctor()
15   IL_0006:  stloc.2
16   IL_0007:  ldloc.2
17   IL_0008:  newobj     instance void ConsoleApplication1.Person::.ctor()
18   IL_000d:  stloc.3
19   IL_000e:  ldloc.3
20   IL_000f:  ldstr      bytearray (71 4E 1E 82 )                                     // qN..
21   // _Person::set_Name
22   IL_0014:  callvirt   instance void ConsoleApplication1.Person::set_Name(string)
23   IL_0019:  nop
24   IL_001a:  ldloc.3
25   IL_001b:  ldc.i4.s   22
26   // _Person::set_Age
27   IL_001d:  callvirt   instance void ConsoleApplication1.Person::set_Age(int32)
28   IL_0022:  nop
29   IL_0023:  ldloc.3
30   // List Add 
31   IL_0024:  callvirt   instance void class 
32 ·[mscorlib]System.Collections.Generic.List`1<class ConsoleApplication1.Person>::Add(!0)
33  // 。。。
34 } // end of method Program::Main

32줄에서 알 수 있듯이 여기는 주로 이 Add 방법입니다. 이전에List에 요소를 추가하는 것은 수동으로 이 방법을 호출했고, 지금은 컴파일러가 우리를 도와 호출합니다.컬렉션 초기화기를 성공적으로 컴파일하려면 다음과 같은 몇 가지 기본 조건이 필요합니다.
1 Icollection 또는 일반 Icollection 인터페이스를 실현해야 한다. 이렇게 하면 집합이 Add 방법을 지원할 수 있다. 이것은 이상적인 상황이다.
2 IEnumerable 또는 일반 버전의 IEnumerable 인터페이스 유형에 하나 이상의 Add 방법이 있습니다. 1 요구 사항이 없는 인터페이스라도 가능합니다.이것은 비교적 느슨한 상황이다.

3. 요약


집합 초기화기와 대상 초기화기의 공통점은 모두 컴파일러가 만든 기술이라는 것을 알 수 있다.이전의 문법이 만들어낸 효과와 아무런 본질적인 차이가 없지만 집합 초기화기가 만들어낸 모든 대상 이름을 우리는 모른다. [컴파일러가 규칙에 따라 해당하는 대상 이름을 만들어서 우리는 직접 인용할 수 없다.]

좋은 웹페이지 즐겨찾기