![](/img/trans.png)
[英]“InvalidCastException: Cannot cast from source type to destination type.” when loading serialized data
[英]Type Data From InvalidCastException
问题很简单:有没有办法从InvalidCastException
获取有问题的System.Type
? 我希望能够以诸如“Expected {to-type}; found {from-type}”之类的格式显示有关失败类型转换的信息,但我找不到访问所涉及类型的方法。
编辑:我需要能够访问所涉及的类型的原因是因为我有一些时间有关于较短名称的信息。 例如,我想说类型实际上是smallint
而不是RFSmallInt
类型。 而不是错误消息
Unable to cast object of type 'ReFactor.RFSmallInt' to type 'ReFactor.RFBigInt'.
我其实想要展示
Expected bigint; recieved smallint.
一种解决方案可能是实现Cast函数,如果转换不成功,它会为您提供信息:
static void Main(string[] args)
{
try
{
string a = Cast<string>(1);
}
catch (InvalidCastExceptionEx ex)
{
Console.WriteLine("Failed to convert from {0} to {1}.", ex.FromType, ex.ToType);
}
}
public class InvalidCastExceptionEx : InvalidCastException
{
public Type FromType { get; private set; }
public Type ToType { get; private set; }
public InvalidCastExceptionEx(Type fromType, Type toType)
{
FromType = fromType;
ToType = toType;
}
}
static ToType Cast<ToType>(object value)
{
try
{
return (ToType)value;
}
catch (InvalidCastException)
{
throw new InvalidCastExceptionEx(value.GetType(), typeof(ToType));
}
}
我用自定义异常完成了这种事情:
public class TypeNotImplementedException : Exception {
public Type ToType { get { return _ToType; } }
private readonly Type _ToType;
public Type FromType { get { return _FromType; } }
private readonly Type _FromType;
public override System.Collections.IDictionary Data {
get {
var data = base.Data ?? new Hashtable();
data["ToType"] = ToType;
data["FromType"] = FromType;
return data;
}
}
public TypeNotImplementedException(Type toType, Type fromType, Exception innerException)
: base("Put whatever message you want here.", innerException) {
_ToType = toType;
_FromType = fromType;
}
}
class Program {
private static T Cast<T>(object obj) {
try {
return (T)obj;
}
catch (InvalidCastException ex) {
throw new TypeNotImplementedException(typeof(T), obj.GetType(), ex);
}
}
static void Main(string[] args) {
try {
Cast<string>("hello world" as object);
Cast<string>(new object());
}
catch (TypeNotImplementedException ex) {
Console.WriteLine(ex);
}
}
}
消息本身以适合显示的格式提供给您。 例如:
Unable to cast object of type 'System.String' to type 'System.Xml.Linq.XElement'.
我不相信有一种编程方式来访问所涉及的类型(并且不,我不建议解析消息)。
特别是,遗憾的是, Data
属性没有附带的信息。
所以基本上,你的选择是:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.