我有字符串,可能是int,datetime,boolean,byte等'。
如何在不使用每种类型的TryParse的情况下验证字符串是否可以转换为这些类型?
答案 0 :(得分:3)
除了在try catch块中调用Parse()(一个可怕的想法),我认为唯一的选择是编写自己的解析算法(也是一个坏主意)。
为什么不想使用TryParse方法?
答案 1 :(得分:3)
public class GenericsManager
{
public static T ChangeType<T>(object data)
{
T value = default(T);
if (typeof(T).IsGenericType &&
typeof(T).GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
{
value = (T)Convert.ChangeType(data, Nullable.GetUnderlyingType(typeof(T)));
}
else
{
if (data != null)
{
value = (T)Convert.ChangeType(data, typeof(T));
}
}
return value;
}
}
这里没有大量用处,但我想你可以使用它,并验证结果不等于该类型的默认值。
但是,tryparse要好得多,而且要达到你要做的目的。
答案 2 :(得分:1)
您可以使用正则表达式来确定它们的类型。虽然如果你需要在int和byte之间进行区分,如果值小于255,那将会有点棘手。
答案 3 :(得分:0)
您可以在 TryParse 和正则表达式之间使用混合。它不是一个漂亮的代码,但速度很快,你可以在任何地方使用这个方法。
Boolean 类型存在问题。 0 或 1 可以表示布尔值,但也可以来自 Byte 类型。我解析了 true 和 false 文本值,但是根据您的业务规则,您应该决定什么是最适合您的。
public static Type getTypeFromString(String s)
{
if (s.Length == 1)
if (new Regex(@"[^0-9]").IsMatch(s)) return Type.GetType("System.Char");
else
return Type.GetType("System.Byte", true, true);
if (new Regex(@"^(\+|-)?\d+$").IsMatch(s))
{
Decimal d;
if (Decimal.TryParse(s, out d))
{
if (d <= Byte.MaxValue && d >= Byte.MinValue) return Type.GetType("System.Byte", true, true);
if (d <= UInt16.MaxValue && d >= UInt16.MinValue) return Type.GetType("System.UInt16", true, true);
if (d <= UInt32.MaxValue && d >= UInt32.MinValue) return Type.GetType("System.UInt32", true, true);
if (d <= UInt64.MaxValue && d >= UInt64.MinValue) return Type.GetType("System.UInt64", true, true);
if (d <= Decimal.MaxValue && d >= Decimal.MinValue) return Type.GetType("System.Decimal", true, true);
}
}
if (new Regex(@"^(\+|-)?\d+[" + NumberFormatInfo.CurrentInfo.CurrencyDecimalSeparator + @"]\d*$").IsMatch(s))
{
Double d;
if (Double.TryParse(s, out d))
{
if (d <= Single.MaxValue && d >= Single.MinValue) return Type.GetType("System.Single", true, true);
if (d <= Double.MaxValue && d >= Double.MinValue) return Type.GetType("System.Double", true, true);
}
}
if(s.Equals("true",StringComparison.InvariantCultureIgnoreCase) || s.Equals("false",StringComparison.InvariantCultureIgnoreCase))
return Type.GetType("System.Boolean", true, true);
DateTime dateTime;
if(DateTime.TryParse(s, out dateTime))
return Type.GetType("System.DateTime", true, true);
return Type.GetType("System.String", true, true);
}