简体   繁体   中英

Can Convert.ChangeType be run in an unchecked context?

I have what is effectively a deserialization class for a custom messaging protocol. This class uses reflection to inspect the properties of the class and the attributes for the protocol mapping. This is working fine except when the value is an unsigned integer (32 or 64) and is being cast to an integer (32 or 64).

I could test (eg if x is int ) the property types and branch off the code for these numeric types to perform casts in an unchecked block, but I would much rather keep the code simple and find a way to use the existing Convert.ChangeType(value, convertToType) logic. Is there a way to have this converter ignore numeric overflows? Or is there an alternative to casting using types known only at runtime?

NB: I realize that there is a root cause here that needs fixing but we do not currently have the ability to change the source of the data, the transport type or the messaging protocol.

I guess it's a developer instinct to not want to switch on the is keyword, been there myself. I would suggest doing it anyway. If you were not using reflection, I would understand the deliberation in introducing it, but if you are already using reflection anyway...

If you know (or guess) that the uint will not be larger than int.MaxValue, then you can use Convert.ToInt32 . You should also catch the 'OverflowExceptions`, just in case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM