C# string Parsing to variable types

后端 未结 7 737
暖寄归人
暖寄归人 2021-02-02 04:55

I want to parse a string into a type easily, but I don\'t want to write wrapper code for each type, I just want to be able to do \"1234\".Parse() or the like and have it return

7条回答
  •  南笙
    南笙 (楼主)
    2021-02-02 05:12

    There are two problems with that scenario. First you would have to write some code to analyse the string to try to determine what data types it would be possible to parse into, and then some logic to choose one of them. (The string "1" for example would be parsable to byte, sbyte, int, uint, long, ulong, float, double and Decimal. Even worse, the string "4.8.12" would be parsable to several numeric types as well as DateTime in three different ways resulting in totally different values...)

    The other problem is that any method capable of doing that would have to return the value boxed in an object, so you would still need wrapper code for each data type just to unbox the value.

    Besides, what would you do with a value where you have no control over the type? So, don't try to make this simpler, it only gets a lot more complicated.

提交回复
热议问题