我正在使用一个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);
}
这是ExceptionError类中的引发InvalidCastException的行:
Dictionary<string,string> data = (Dictionary<string, string>)exceptionArgs[7];
// exceptionArgs[7] is Exception.Data
这是我收到的实际错误:
无法将类型为“ System.Collections.ListDictionaryInternal”的对象转换为类型为“ System.Collections.Generic.Dictionary`2 [System.String,System.String]”。
我找不到关于ListDictionaryInternal的任何信息,我完成的大部分Google搜索都指向System.Collections.Specialized.ListDictionary,它会产生自己的问题。有谁知道有关ListDictionaryInternal的信息,或者您可以帮助我将e.Data传递到我的ExceptionError类中吗?
基本上,of的值Exception.Data
不是Dictionary<string, string>
-,所以当您将其强制转换为时Dictionary<string, string>
,会遇到此异常。
该属性本身仅声明为type IDictionary
。您不应该假设它是Dictionary<string, string>
。您应该修正ExceptionError
班级以避免这种假设。据记录,键通常是字符串,但是不能保证-同样,不能保证值是字符串。
您可以通过仅转换适当的条目来执行从“IDictionary
到”的“安全”转换Dictionary<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);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句