问题很简单:有没有办法从System.Type
获取有问题的InvalidCastException
?我希望能够以诸如“Expected {to-type}; found {from-type}”之类的格式显示有关失败类型转换的信息,但我找不到一种方法来访问所涉及的类型。
编辑:我需要能够访问所涉及的类型的原因是因为我有一些关于较短名称的信息。例如,我想说类型实际上是RFSmallInt
,而不是类型smallint
。而不是错误消息
Unable to cast object of type 'ReFactor.RFSmallInt' to type 'ReFactor.RFBigInt'.
我其实想要显示
Expected bigint; recieved smallint.
答案 0 :(得分:7)
一个解决方案可能是实现一个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));
}
}
答案 1 :(得分:2)
我用自定义异常完成了这种事情:
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);
}
}
}
答案 2 :(得分:1)
消息本身以合理的格式显示。例如:
Unable to cast object of type 'System.String' to type 'System.Xml.Linq.XElement'.
我不相信有一种程序化方式来访问所涉及的类型(不,我不建议解析该消息)。
特别是,遗憾的是,Data
属性没有附带信息。
所以基本上,你的选择是: