我正在开发一个工具,需要将字符串值转换为它们对应的对象类型。例如,将像"2008-11-20T16:33:21Z"
这样的字符串转换为DateTime
值。数值型的字符串如"42"
和"42.42"
需要分别转换为Int32
和Double
类型的值。
检测一个字符串是整数还是数字的最佳和最有效的方法是什么?Int32.TryParse
或Double.TryParse
是否是正确选择?
我正在开发一个工具,需要将字符串值转换为它们对应的对象类型。例如,将像"2008-11-20T16:33:21Z"
这样的字符串转换为DateTime
值。数值型的字符串如"42"
和"42.42"
需要分别转换为Int32
和Double
类型的值。
检测一个字符串是整数还是数字的最佳和最有效的方法是什么?Int32.TryParse
或Double.TryParse
是否是正确选择?
Int.TryParse
和 Double.TryParse
具有实际返回数字的好处。
像 Regex.IsMatch("^\d+$")
这样的内容有一个缺点,你仍然需要再次解析字符串才能获取值。
就效率而言,是的,TryParse通常是首选。
如果您可以提前知道目标类型(例如通过反射),但不想使用大型switch
块,那么您可能会对使用TypeConverter
感兴趣-例如:
DateTime foo = new DateTime(2008, 11, 20);
TypeConverter converter = TypeDescriptor.GetConverter(foo);
string s = converter.ConvertToInvariantString(foo);
object val = converter.ConvertFromInvariantString(s);
这里有一个有趣的链接支持这一点。
public static class ConvertFromString
{
public static T? ConvertTo<T>(this String numberToConvert) where T : struct
{
T? returnValue = null;
MethodInfo neededInfo = GetCorrectMethodInfo(typeof(T));
if (neededInfo != null && !numberToConvert.IsNullOrEmpty())
{
T output = default(T);
object[] paramsArray = new object[2] { numberToConvert, output };
returnValue = new T();
object returnedValue = neededInfo.Invoke(returnValue.Value, paramsArray);
if (returnedValue is Boolean && (Boolean)returnedValue)
{
returnValue = (T)paramsArray[1];
}
else
{
returnValue = null;
}
}
return returnValue;
}
}
GetCorrectMethodInfo 的实现大致如下:
private static MethodInfo GetCorrectMethodInfo(Type typeToCheck)
{
MethodInfo returnValue = someCache.Get(typeToCheck.FullName);
if(returnValue == null)
{
Type[] paramTypes = new Type[2] { typeof(string), typeToCheck.MakeByRefType() };
returnValue = typeToCheck.GetMethod("TryParse", paramTypes);
if (returnValue != null)
{
CurrentCache.Add(typeToCheck.FullName, returnValue);
}
}
return returnValue;
}
使用方法如下:
decimal? converted = someString.ConvertTo<decimal>();
虽然我不太喜欢自吹自擂,但是我已经在这里详细解释了: