C# string Parsing to variable types

后端 未结 7 734
暖寄归人
暖寄归人 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:30

    This trick should work. It uses the type of the variable you're assigning to automagically:

    public static class StringExtensions {
        public static ParsedString Parse(this string s) {
            return new ParsedString(s);
        }
    }
    public class ParsedString {
        string str;
        public ParsedString(string s) {
            str = s;
        }
        public static implicit operator int(ParsedString s) {
            return int.Parse(s.str);
        }
        public static implicit operator double(ParsedString s) {
            return double.Parse(s.str);
        }
        public static implicit operator short(ParsedString s) {
            return short.Parse(s.str);
        }
        public static implicit operator byte(ParsedString s) {
            return byte.Parse(s.str);
        }
        // ... add other supported types ...
    }
    

    Usage:

    int p = "1234".Parse();
    

    I would prefer explicitly parsing using framework provided methods rather than relying on these kind of tricks.

提交回复
热议问题