Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

308
Views
¿Cómo inicializar un diccionario concurrente? Error: "No se puede acceder al método privado 'Agregar' aquí"

Tengo una clase estática en la que estoy usando diccionarios como tablas de búsqueda para mapear entre tipos .NET y tipos SQL. He aquí un ejemplo de dicho diccionario:

 private static readonly Dictionary<Type, string> SqlServerMap = new Dictionary<Type, string> { {typeof (Boolean), "bit"}, {typeof (Byte[]), "varbinary(max)"}, {typeof (Double), "float"}, {typeof (Byte), "tinyint"}, {typeof (Int16), "smallint"}, {typeof (Int32), "int"}, {typeof (Int64), "bigint"}, {typeof (Decimal), "decimal"}, {typeof (Single), "real"}, {typeof (DateTime), "datetime2(7)"}, {typeof (TimeSpan), "time"}, {typeof (String), "nvarchar(MAX)"}, {typeof (Guid), "uniqueidentifier"} };

Luego tengo un método público a continuación que pasa un tipo .NET y devuelve el valor de cadena del tipo de MS SQL Server correspondiente usando este diccionario. Sin embargo, dado que esto se usa como una tabla de búsqueda para realizar consultas a la base de datos, creo que tiene sentido convertirlo en un ConcurrentDictionary . Lo cambié a:

 private static readonly IDictionary<Type, string> SqlServerMap = new ConcurrentDictionary<Type, string> { {typeof (Boolean), "bit"}, {typeof (Byte[]), "varbinary(max)"}, {typeof (Double), "float"}, {typeof (Byte), "tinyint"}, {typeof (Int16), "smallint"}, {typeof (Int32), "int"}, {typeof (Int64), "bigint"}, {typeof (Decimal), "decimal"}, {typeof (Single), "real"}, {typeof (DateTime), "datetime2(7)"}, {typeof (TimeSpan), "time"}, {typeof (String), "nvarchar(MAX)"}, {typeof (Guid), "uniqueidentifier"} };

Pero ahora subraya todo lo rojo dentro de {} (es decir, todos los pares de valores clave del ConcurrentDictionary ) y el error es:

No se puede acceder al método privado 'Agregar' aquí

No creo que sea porque lo inicialicé como private static readonly , porque acabo de probar haciendo una versión public static y obtuve el mismo error.

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Prueba esto

 private static readonly IDictionary<Type, string> SqlServerMap = new ConcurrentDictionary<Type, string>( new Dictionary<Type, string>() { {typeof(Boolean ), "bit" }, {typeof(Byte[] ), "varbinary(max)" }, {typeof(Double ), "float" }, {typeof(Byte ), "tinyint" }, {typeof(Int16 ), "smallint" }, {typeof(Int32 ), "int" }, {typeof(Int64 ), "bigint" }, {typeof(Decimal ), "decimal" }, {typeof(Single ), "real" }, {typeof(DateTime), "datetime2(7)" }, {typeof(TimeSpan), "time" }, {typeof(String ), "nvarchar(MAX)" }, {typeof(Guid ), "uniqueidentifier"} } );

Actualizado: si usa C#6 (compilador Roslyn 2.0), puede usar los nuevos Inicializadores de diccionario.

 private static readonly IDictionary<Type, string> SqlServerMap = new ConcurrentDictionary<Type, string> { [typeof(Boolean )] = "bit" , [typeof(Byte[] )] = "varbinary(max)" , [typeof(Double )] = "float" , [typeof(Byte )] = "tinyint" , [typeof(Int16 )] = "smallint" , [typeof(Int32 )] = "int" , [typeof(Int64 )] = "bigint" , [typeof(Decimal )] = "decimal" , [typeof(Single )] = "real" , [typeof(DateTime)] = "datetime2(7)" , [typeof(TimeSpan)] = "time" , [typeof(String )] = "nvarchar(MAX)" , [typeof(Guid )] = "uniqueidentifier" };

Ejemplo https://dotnetfiddle.net/9ZgjsR

over 4 years ago · Santiago Trujillo Report

0

El inicializador de la colección que está utilizando para completar la colección solo funciona si la colección tiene un método Add de una firma y accesibilidad adecuadas. ConcurrentDictionary no tiene un método Add público, por lo que no podrá usar un inicializador de colección con él.

Puede proporcionar algunos datos iniciales pasando un IEnumerable<KeyValuePair<TKey, TValue>> como parámetro al constructor, o puede llamar a TryAdd (o AddOrUpdate , o cualquiera de los otros métodos con Add en el nombre) en un bucle después de creando el ConcurrentDictionary .

over 4 years ago · Santiago Trujillo Report

0

Como ejemplo de código para la respuesta aceptada de Servy, para inicializar un ConcurrentDictionary en la creación de instancias, puede pasar un tipo que impida IEnumerable (como una List ) de tipos KeyValuePair al constructor:

 private static readonly IDictionary<Type, string> SqlServerMap = new ConcurrentDictionary<Type, string>( new List<KeyValuePair<Type, string>> { new KeyValuePair<Type, string>(typeof(Boolean), "bit"), new KeyValuePair<Type, string>(typeof(Boolean), "bit"), new KeyValuePair<Type, string>(typeof(Byte[]), "varbinary(max)"), new KeyValuePair<Type, string>(typeof(Double), "float"), new KeyValuePair<Type, string>(typeof(Byte), "tinyint"), new KeyValuePair<Type, string>(typeof(Int16), "smallint"), new KeyValuePair<Type, string>(typeof(Int32), "int"), new KeyValuePair<Type, string>(typeof(Int64), "bigint"), new KeyValuePair<Type, string>(typeof(Decimal), "decimal"), new KeyValuePair<Type, string>(typeof(Single), "real"), new KeyValuePair<Type, string>(typeof(DateTime), "datetime2(7)"), new KeyValuePair<Type, string>(typeof(TimeSpan), "time"), new KeyValuePair<Type, string>(typeof(String), "nvarchar(MAX)"), new KeyValuePair<Type, string>(typeof(Guid), "uniqueidentifier") });
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!