What's a great way to convert a string to a number in C#?
I'm 开发者_如何学Pythonfamiliar with:
Convert.ToInt32(texthere);
But is there another cleaner way to do it? I like having readable code for coworkers and I'm always on the lookout for anything that'll make my work seem more obvious.
What's not obvious about Convert.ToInt32
?
Convert
this value To
an Int32
?
You can also use Parse and TryParse methods of int, double, float and decimal types.
int.TryParse / double.TryParse
Int.parse, float.parse and so forth.
Personally I would use the standard methods stated (Convert.ToInt32, double.TryParse etc), but if you want an alternative ...
You could add an extension method, something like this (not tested it):
public static class Extensions
{
public static int ConvertStringToInt(this string s)
{
return Convert.ToInt32(s);
}
public static long ConvertStringToLong(this string s)
{
return Convert.ToInt64(s);
}
}
And then you could:
string test = "1234";
int testToInt = test.ConvertStringToInt();
long testToLong = test.ConvertStringToLong();
精彩评论