c# - Type Data From InvalidCastException -
the question pretty simple: there way problematic system.type
s invalidcastexception
? want able display information failed type casting in format such "expected {to-type}; found {from-type}", cannot find way access types involved.
edit: reason need able access types involved because have information shorter names times. example, instead of type rfsmallint
, want type smallint
. instead of error message
unable cast object of type 'refactor.rfsmallint' type 'refactor.rfbigint'.
i want display
expected bigint; recieved smallint.
one solution implement cast function gives information if cast doesn't succeed:
static void main(string[] args) { try { string = cast<string>(1); } catch (invalidcastexceptionex ex) { console.writeline("failed convert {0} {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)); } }
Comments
Post a Comment