2009-06-24 74 views
0

我有可能是int,datetime,布尔,字节等字符串'。如何验证字符串可以转换为特定类型?

我怎样才能验证字符串可以转换成这些类型而不使用每种类型的TryParse?

+3

是否有一个特别的原因,您不想使用TryParse?这是最简单,最强大的方式,也可能是最快的方法之一。 – 2009-06-24 10:11:00

回答

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要好得多,并且要达到您所要做的。

3

除了在try catch块(一个可怕的想法)内调用Parse(),我认为唯一的选择是编写自己的解析算法(也是一个坏主意)。

为什么你不想使用TryParse方法?

+0

,因为我有很多可能的类型,所以使用解析/ tryparsing是很多代码来编写的,所以在使用这种丑陋的方式之前,我正在寻找更好的代码。 – Tamir 2009-06-24 10:13:13

+0

我认为你有很多if/else语句。我不认为有一个更干净的方法来做到这一点。 – AndrewS 2009-06-24 10:27:05

1

您可以使用正则表达式来确定它们可能是什么类型。虽然这将是一个有点麻烦,如果你需要一个int和一个字节之间者区分如果该值小于255

0

您可以在TryParse和正则表达式之间混用。这不是一个漂亮的代码,但速度很快,并且您可以在任何地方使用该方法。

有关于布尔类型的问题。 或可以表示布尔值,但也可以是类型字节。我解析了truefalse文本值,但是关于您的业务规则,您应该决定什么是最适合您的。

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); 
     } 
相关问题