“词典”中已添加具有相同键的项目

本文关键字:项目 词典 添加 | 更新日期: 2023-09-27 17:57:18

我正在开发sql clr应用程序,与sql集成后,我收到此错误(对于英语,它可以工作,但是在将Unicode添加到字典时出现问题):

**Msg 6522, Level 16, State 2, Line 1
A .NET Framework error occurred during execution of user-defined routine or     aggregate "SqlCompare": 
System.ArgumentException: An item with the same key has already been added.
System.ArgumentException: 
   at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
   at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value,      Boolean add)
   at System.Collections.Generic.Dictionary`2.Add(TKey key, TValue value)
   at Translate_Class_NUM..ctor()
   at StringPercentageCompare..ctor()
   at UserDefinedFunctions.SqlComparison()**
 here is my code in c#
private   Dictionary<string, string> MyDictionary;
//private string[,] MyArray;
public Translate_Class_NUM()
{
    MyDictionary.Add("?", "01");
    MyDictionary.Add("?", "02");
    MyDictionary.Add("?", "03");
    MyDictionary.Add("?", "04");
    MyDictionary.Add("?", "05")
}

在SQL服务器代码是 创建程序集DBDB_DeDuplication授权 dbo来自 'E:''Projects''DBDB_DeDuplication''DBDB_DeDuplication''obj''Debug''DBDB_DeDuplication.dll'带PERMISSION_SET = 安全去

创建函数 SqlCompare() 返回 nvarchar(50)作为外部名称DBDB_DeDuplication.UserDefinedFunctions.SqlComparison;去

选择"dbo"。SqlCompare();去

提前致谢

“词典”中已添加具有相同键的项目

这段代码对我来说很好用:

Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("ಅ","01");
dict.Add("ಇ","02");

正如我之前在注释中试图解释的那样,您的 Unicode 字符串不得以您期望的方式传递到编译器。有时,这可能是由于 C# 源文件使用 ASCII 编码或其他非 Unicode 支持编码保存。若要保证结果,请使用 C# Unicode 文本编码(U+0000 到 U+FFFF)。

如果您不知道如何获取等效的 Unicode 转义序列,可以使用以下代码:

static string EncodeNonAsciiCharacters( string value )
{
    StringBuilder sb = new StringBuilder();
    foreach( char c in value ) {
        if( c > 127 ) {
            // This character is too big for ASCII
            string encodedValue = "''u" + ((int) c).ToString( "x4" );
            sb.Append( encodedValue );
        }
        else {
            sb.Append( c );
        }
    }
    return sb.ToString();
}
Console.WriteLine(EncodeNonAsciiCharacters("ಅ"));
'u0c85
Console.WriteLine(EncodeNonAsciiCharacters("ಇ"));
'u0c87

因此,您可以将源代码的更安全版本编写为:

Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("'u0c85","01");
dict.Add("'u0c87","02");