Wszystkie możliwe składnie inicjalizacji tablicy

Jakie są wszystkie składnie inicjalizacji tablicy, które są możliwe w C#?

Author: Stephen Kennedy, 2011-04-15

13 answers

Są to bieżące metody deklaracji i inicjalizacji dla prostej tablicy.

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

Zauważ, że istnieją inne techniki uzyskiwania tablic, takie jak rozszerzenia Linq ToArray() na IEnumerable<T>.

Zauważ również, że w powyższych deklaracjach, pierwsze dwa mogą zastąpić string[] po lewej stronie var (C# 3+), ponieważ informacje po prawej stronie są wystarczające, aby wywnioskować właściwy typ. Trzecia linia musi być zapisana jako wyświetlona, ponieważ sama składnia inicjalizacji tablicy nie wystarcza do zaspokoić wymagania kompilatora. Czwarty może również korzystać z wnioskowania. Więc jeśli jesteś w tej całej zwięzłości, powyższe może być napisane jako

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 
 519
Author: Anthony Pegram,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-12 14:16:40

Składnia tworzenia tablicy w C#, które są wyrażeniami to:

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

W pierwszym z nich Rozmiar może być dowolną nieujemną wartością całkową, a elementy tablicy są inicjalizowane wartościami domyślnymi.

W drugim, rozmiar musi być stały, a liczba podanych elementów musi się zgadzać. Musi istnieć niejawna konwersja z podanych elementów na dany typ elementu tablicy.

W trzecim, elementy muszą być niejawnie zamienione na rodzaj elementu, a jego wielkość jest określona na podstawie liczby podanych elementów.

W czwartym z nich Typ elementu tablicy jest wnioskowany przez obliczenie najlepszego typu, jeśli istnieje, ze wszystkich podanych elementów, które mają typy. Wszystkie elementy muszą być niejawnie zamienne do tego typu. Wielkość określa się na podstawie liczby podanych elementów. Składnia ta została wprowadzona w C # 3.0.

Istnieje również składnia, która może być używana tylko w deklaracji:

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

The elementy muszą być niejawnie zamieniane na typ elementu. Wielkość określa się na podstawie liczby podanych elementów.

Nie ma przewodnika "wszystko w jednym"

Odsyłam do specyfikacji C# 4.0, sekcja 7.6.10.4 "Array Creation Expressions".

 367
Author: Eric Lippert,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-10-25 02:51:05

Niepuste tablice

  • 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 } nie można go skompilować. Zamiast tego użyj int[] data5 = { 1, 2, 3 }.

Puste tablice

  • var data6 = new int[0]
  • var data7 = new int[] { }
  • var data8 = new [] { } i int[] data9 = new [] { } nie są kompilowalne.

  • var data10 = { } nie można go skompilować. Zamiast tego użyj int[] data11 = { }.

Jako argument metoda

Tylko wyrażenia, które mogą być przypisane za pomocą słowa kluczowego var mogą być przekazywane jako argumenty.

  • Foo(new int[2])
  • Foo(new int[2] { 1, 2 })
  • Foo(new int[] { 1, 2 })
  • Foo(new[] { 1, 2 })
  • Foo({ 1, 2 }) nie można kompilować
  • Foo(new int[0])
  • Foo(new int[] { })
  • Foo({}) Nie można kompilować
 87
Author: kiss my armpit,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-08-14 18:21:50
Enumerable.Repeat(String.Empty, count).ToArray()

Utworzy tablicę pustych łańcuchów powtarzających się razy "count". W przypadku, gdy chcesz zainicjalizować tablicę z tą samą, ale specjalną wartością domyślną elementu. Ostrożnie z typami odniesienia, wszystkie elementy będą odnosiły się do tego samego obiektu.

 35
Author: Atomosk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-05-06 09:05:32
var contacts = new[]
{
    new 
    {
        Name = " Eugene Zabokritski",
        PhoneNumbers = new[] { "206-555-0108", "425-555-0001" }
    },
    new 
    {
        Name = " Hanying Feng",
        PhoneNumbers = new[] { "650-555-0199" }
    }
};
 15
Author: Nahid Camalli,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-31 13:47:32

W przypadku, gdy chcesz zainicjalizować stałą tablicę wstępnie zainicjalizowanych równych (nie-null lub innych niż default) elementów, użyj tego:

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

Proszę również wziąć udział w tej dyskusji.

 11
Author: Shimmy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-31 13:28:09

Przykład tworzenia tablicy niestandardowej klasy

Poniżej znajduje się definicja klasy.

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

W ten sposób można zainicjalizować tablicę:

private DummyUser[] arrDummyUser = new DummyUser[]
{
    new DummyUser{
       email = "[email protected]",
       language = "English"
    },
    new DummyUser{
       email = "[email protected]",
       language = "Spanish"
    }
};
 7
Author: Amol,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-22 14:53:18
int[] array = new int[4]; 
array[0] = 10;
array[1] = 20;
array[2] = 30;

Lub

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

Lub

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

Oraz w tablicy wielowymiarowej

    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)"
 4
Author: Brad Larson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-27 22:39:37

Powtórz Bez LINQ :

float[] floats = System.Array.ConvertAll(new float[16], v => 1.0f);
 4
Author: Nick Shalimov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-26 14:53:25
For Class initialization:
var page1 = new Class1();
var page2 = new Class2();
var pages = new UIViewController[] { page1, page2 };
 2
Author: Sanjay Shrivastava,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-13 03:35:25

Można również tworzyć tablice dynamiczne, tzn. można najpierw zapytać użytkownika o rozmiar tablicy przed jej utworzeniem.

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();
 0
Author: Pushpendra7974,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-22 14:54:02

Trywialne rozwiązanie z wyrażeniami. Zauważ, że dzięki NewArrayInit możesz tworzyć tylko jednowymiarową tablicę.

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
 0
Author: unsafePtr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-14 21:25:42

Inny sposób tworzenia i inicjalizacji tablicy obiektów. Jest to podobne do przykładu , który @Amol opublikował powyżej , z tą różnicą, że ten używa konstruktorów. Odrobina polimorfizmu, nie mogłem się oprzeć.

IUser[] userArray = new IUser[]
{
    new DummyUser("[email protected]", "Gibberish"),
    new SmartyUser("[email protected]", "Italian", "Engineer")
};

Klasy dla kontekstu:

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;
}
 0
Author: Nick Alexeev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-16 01:58:17