Puedo escribir lo siguiente para inicializar un List<KeyValuePair<string, string>> en un inicializador de campo:
List<KeyValuePair<string, string>> lst = new() { new("Key1", "Value1"), new("Key2", "Value2") } aprovechando las new expresiones de tipo objetivo para las estructuras List<> contenedoras y KeyValuePair<> individuales.
¿Es posible inicializar de manera similar una matriz? Las new expresiones de tipo objetivo no se pueden usar para la matriz en sí, porque se debe inicializar una matriz.
Pero lo siguiente, usando matrices implícitamente tipadas, no se compila:
KeyValuePair<string, string>[] arr = new [] { new("Key1", "Value1"), new("Key2", "Value2") }con:
CS0826 No se encontró el mejor tipo para la matriz tipificada implícitamente
Puede eliminar la parte new[] :
using System.Collections.Generic; KeyValuePair<string, string>[] arr = { new("Key1", "Value1"), new("Key2", "Value2") };Sin embargo, eso solo es válido como parte de una declaración de variable, que permite un array_initializer como el valor inicial, sin la necesidad de un array_creation_expression . Las declaraciones de variables incluyen campos, por supuesto:
public class Test { private readonly KeyValuePair<string, string>[] arr = { new("Key1", "Value1"), new("Key2", "Value2") }; }