2009-06-24 76 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); 
     } 
相關問題