Programing

가능한 모든 배열 초기화 구문

crosscheck 2020. 10. 2. 21:34
반응형

가능한 모든 배열 초기화 구문


C #으로 가능한 모든 배열 초기화 구문은 무엇입니까?


다음은 간단한 배열에 대한 현재 선언 및 초기화 메서드입니다.

string[] array = new string[2]; // creates array of length 2, default values
string[] array = new string[] { "A", "B" }; // creates populated array of length 2
string[] array = { "A" , "B" }; // creates populated array of length 2
string[] array = new[] { "A", "B" }; // created populated array of length 2

.NET의 Linq ToArray()확장 과 같은 배열을 얻는 다른 기술이 IEnumerable<T>있습니다.

또한 위의 선언에서 처음 두 개 string[]는 왼쪽의를 var(C # 3+)로 대체 할 수 있습니다. 오른쪽의 정보는 적절한 형식을 추론하기에 충분하기 때문입니다. 세 번째 줄은 표시된대로 작성해야합니다. 배열 초기화 구문만으로는 컴파일러의 요구를 충족하기에 충분하지 않기 때문입니다. 네 번째는 추론을 사용할 수도 있습니다. 따라서 전체적인 간결함을 알고 있다면 위의 내용을 다음과 같이 작성할 수 있습니다.

var array = new string[2]; // creates array of length 2, default values
var array = new string[] { "A", "B" }; // creates populated array of length 2
string[] array = { "A" , "B" }; // creates populated array of length 2
var array = new[] { "A", "B" }; // created populated array of length 2 

식인 C #의 배열 생성 구문 은 다음과 같습니다.

new int[3]
new int[3] { 10, 20, 30 }
new int[] { 10, 20, 30 }
new[] { 10, 20, 30 }

첫 번째에서 크기는 음이 아닌 정수 값이 될 수 있으며 배열 요소는 기본값으로 초기화됩니다.

두 번째에서 크기는 상수 여야하며 주어진 요소의 수가 일치해야합니다. 지정된 요소에서 지정된 배열 요소 유형으로의 암시 적 변환이 있어야합니다.

세 번째에서 요소는 암시 적으로 요소 유형으로 변환 할 수 있어야하며 크기는 주어진 요소 수에 따라 결정됩니다.

네 번째 항목에서 배열 요소의 유형은 유형이있는 모든 주어진 요소 중 최상의 유형이있는 경우 계산하여 추론됩니다. 모든 요소는 암시 적으로 해당 유형으로 변환 할 수 있어야합니다. 크기는 주어진 요소의 수에 따라 결정됩니다. 이 구문은 C # 3.0에서 도입되었습니다.

선언에서만 사용할 수있는 구문도 있습니다.

int[] x = { 10, 20, 30 };

요소는 암시 적으로 요소 유형으로 변환 할 수 있어야합니다. 크기는 주어진 요소의 수에 따라 결정됩니다.

올인원 가이드가 없습니다

C # 4.0 사양, 7.6.10.4 "배열 생성 표현식"섹션을 참조하십시오.


비어 있지 않은 배열

  • var data0 = new int[3]

  • var data1 = new int[3] { 1, 2, 3 }

  • var data2 = new int[] { 1, 2, 3 }

  • var data3 = new[] { 1, 2, 3 }

  • var data4 = { 1, 2, 3 }컴파일 할 수 없습니다. int[] data5 = { 1, 2, 3 }대신 사용하십시오 .

빈 배열

  • var data6 = new int[0]
  • var data7 = new int[] { }
  • var data8 = new [] { }int[] data9 = new [] { }컴파일 가능한 없습니다.

  • var data10 = { }컴파일 할 수 없습니다. int[] data11 = { }대신 사용하십시오 .

메서드의 인수로

var키워드 로 할당 할 수있는 표현식 만 인수로 전달할 수 있습니다.

  • Foo(new int[2])
  • Foo(new int[2] { 1, 2 })
  • Foo(new int[] { 1, 2 })
  • Foo(new[] { 1, 2 })
  • Foo({ 1, 2 }) 컴파일 할 수 없습니다
  • Foo(new int[0])
  • Foo(new int[] { })
  • Foo({}) 컴파일 할 수 없습니다

Enumerable.Repeat(String.Empty, count).ToArray()

'count'번 반복되는 빈 문자열 배열을 만듭니다. 동일하지만 특별한 기본 요소 값으로 배열을 초기화하려는 경우. 참조 유형에주의하면 모든 요소가 동일한 객체를 참조합니다.


var contacts = new[]
{
    new 
    {
        Name = " Eugene Zabokritski",
        PhoneNumbers = new[] { "206-555-0108", "425-555-0001" }
    },
    new 
    {
        Name = " Hanying Feng",
        PhoneNumbers = new[] { "650-555-0199" }
    }
};

In case you want to initialize a fixed array of pre-initialized equal (non-null or other than default) elements, use this:

var array = Enumerable.Repeat(string.Empty, 37).ToArray();

Also please take part in this discussion.


Example to create an array of a custom class

Below is the class definition.

public class DummyUser
{
    public string email { get; set; }
    public string language { get; set; }
}

This is how you can initialize the array:

private DummyUser[] arrDummyUser = new DummyUser[]
{
    new DummyUser{
       email = "abc.xyz@email.com",
       language = "English"
    },
    new DummyUser{
       email = "def@email.com",
       language = "Spanish"
    }
};

Repeat without LINQ:

float[] floats = System.Array.ConvertAll(new float[16], v => 1.0f);

int[] array = new int[4]; 
array[0] = 10;
array[1] = 20;
array[2] = 30;

or

string[] week = new string[] {"Sunday","Monday","Tuesday"};

or

string[] array = { "Sunday" , "Monday" };

and in multi dimensional array

    Dim i, j As Integer
    Dim strArr(1, 2) As String

    strArr(0, 0) = "First (0,0)"
    strArr(0, 1) = "Second (0,1)"

    strArr(1, 0) = "Third (1,0)"
    strArr(1, 1) = "Fourth (1,1)"

For Class initialization:
var page1 = new Class1();
var page2 = new Class2();
var pages = new UIViewController[] { page1, page2 };

Another way of creating and initializing an array of objects. This is similar to the example which @Amol has posted above, except this one uses constructors. A dash of polymorphism sprinkled in, I couldn't resist.

IUser[] userArray = new IUser[]
{
    new DummyUser("abc@cde.edu", "Gibberish"),
    new SmartyUser("pga@lna.it", "Italian", "Engineer")
};

Classes for context:

interface IUser
{
    string EMail { get; }       // immutable, so get only an no set
    string Language { get; }
}

public class DummyUser : IUser
{
    public DummyUser(string email, string language)
    {
        m_email = email;
        m_language = language;
    }

    private string m_email;
    public string EMail
    {
        get { return m_email; }
    }

    private string m_language;
    public string Language
    {
        get { return m_language; }
    }
}

public class SmartyUser : IUser
{
    public SmartyUser(string email, string language, string occupation)
    {
        m_email = email;
        m_language = language;
        m_occupation = occupation;
    }

    private string m_email;
    public string EMail
    {
        get { return m_email; }
    }

    private string m_language;
    public string Language
    {
        get { return m_language; }
    }

    private string m_occupation;
}

You can also create dynamic arrays i.e. you can first ask the size of the array from the user before creating it.

Console.Write("Enter size of array");
int n = Convert.ToInt16(Console.ReadLine());

int[] dynamicSizedArray= new int[n]; // Here we have created an array of size n
Console.WriteLine("Input Elements");
for(int i=0;i<n;i++)
{
     dynamicSizedArray[i] = Convert.ToInt32(Console.ReadLine());
}

Console.WriteLine("Elements of array are :");
foreach (int i in dynamicSizedArray)
{
    Console.WriteLine(i);
}
Console.ReadKey();

Trivial solution with expressions. Note that with NewArrayInit you can create just one-dimensional array.

NewArrayExpression expr = Expression.NewArrayInit(typeof(int), new[] { Expression.Constant(2), Expression.Constant(3) });
int[] array = Expression.Lambda<Func<int[]>>(expr).Compile()(); // compile and call callback

참고URL : https://stackoverflow.com/questions/5678216/all-possible-array-initialization-syntaxes

반응형