使用Exception.Data的InvalidCastException Dictionary <string,string>

roa*_*ter 4 .net c# dictionary exception-handling

我有一个我正在玩的Client/Server包,我试图使用Exception.Data将自定义信息传递到一个单独的类(ExceptionError)以传递给MessageBox.

当我尝试连接到服务器而没有实际启动服务器来侦听连接时,以下捕获进程.只是对该部分的疏忽,监听连接不是实际问题,但它向我展示了Exception.Data的问题.

catch (Exception e)
{
    e.Data["SourceFile"] = "Client.cs";
    e.Data["MethodName"] = "Send_CommandToServer";
    e.Data["ExceptionType"] = "Exception";
    object[] exceptionArgs = new object[8] { null, e.InnerException, 
                              e.Message, null, e.Source, e.StackTrace, 
                              e.TargetSite, e.Data };
    ExceptionError.Show(exceptionArgs);
}
Run Code Online (Sandbox Code Playgroud)

以下是ExceptionError类中抛出InvalidCastException的行:

Dictionary<string,string> data = (Dictionary<string, string>)exceptionArgs[7];
 // exceptionArgs[7] is Exception.Data
Run Code Online (Sandbox Code Playgroud)

这是我收到的实际错误:

无法将类型为'System.Collections.ListDictionaryInternal'的对象强制转换为'System.Collections.Generic.Dictionary`2 [System.String,System.String]'.

我找不到任何关于ListDictionaryInternal的信息,我所做的大部分谷歌搜索都指向System.Collections.Specialized.ListDictionary,它产生了自己的问题.有没有人知道关于ListDictionaryInternal的任何信息,或者你能帮助我将e.Data传递给我的ExceptionError类吗?

Jon*_*eet 9

基本上,值Exception.Data不是Dictionary<string, string>- 所以当你投射到时Dictionary<string, string>,你得到这个例外.

属性本身仅被声明为类型IDictionary.你不应该认为它是一个Dictionary<string, string>.你应该修改你的ExceptionError课程以避免这种假设.据记载,键通常是字符串,但不保证 - 同样不能保证值是字符串.

您可以从执行"安全"转变IDictionaryDictionary<string, string>通过转换只有适当的条目:

var dictionary = original.Cast<DictionaryEntry>()
                         .Where(de => de.Key is string && de.Value is string)
                         .ToDictionary(de => (string) de.Key,
                                       de => (string) de.Value);
Run Code Online (Sandbox Code Playgroud)