gpt4 book ai didi

c# - 如何初始化 ConcurrentDictionary?错误 : "Cannot access private method ' Add' here"

转载 作者:可可西里 更新时间:2023-11-01 08:01:52 30 4
gpt4 key购买 nike

我有一个静态类,我在其中使用字典作为查找表以在 .NET 类型和 SQL 类型之间进行映射。这是一个这样的字典的例子:

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"}
};

然后我在下面有一个公共(public)方法,它传入一个 .NET 类型,它使用这个字典返回相应 MS SQL Server 类型的字符串值。但是,由于它被用作进行数据库查询的查找表,我认为将它设为 ConcurrentDictionary 是有意义的。我将其更改为:

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"}
};

但现在它在 {}(即 ConcurrentDictionary 的所有键值对)中用红色下划线,错误是:

Cannot access private method 'Add' here

我不认为这是因为我将其初始化为private static readonly,因为我刚刚通过制作public static版本进行了测试,但我得到了同样的错误。

最佳答案

试试这个

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"}
}
);

更新:如果您使用的是 C#6(Roslyn 2.0 编译器),则可以使用新的字典初始化器。

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"
};

例子 https://dotnetfiddle.net/9ZgjsR

关于c# - 如何初始化 ConcurrentDictionary?错误 : "Cannot access private method ' Add' here",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31815456/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com