Today, I spent lots of time trying to convert string to type. Here below is my finding. Convert.ChangeType() can be used in this situation. Only the following type can be converted successfully: Boolean, Char, SByte, Byte, Int16, Int32, Int64, UInt16, UInt32, UInt64, Single, Double, Decimal, DateTime, and String.
///
/// supported type : Boolean, Char, SByte, Byte, Int16, Int32, Int64, UInt16, UInt32, UInt64, Single, Double, Decimal, DateTime and String.
/// %28VS.71%29.aspx
///
///
internal class StringToType { public static T FromString<T>(string text) { //return (T)Convert.ChangeType(text, typeof(T), CultureInfo.InvariantCulture);
return (T)Convert.ChangeType(text, typeof(T)); }
public static T FromXmlAttribute<T>(XmlNode node, string attributeName) { if (node == null) throw new ArgumentNullException("node");
if (String.IsNullOrEmpty(attributeName)) throw new ArgumentException("Cannot be null or empty", "attributeName");
XmlAttribute attribute = node.Attributes[attributeName]; if (attribute == null) return default(T);
return FromString<T>(attribute.Value); }
public static T FromXAttribute<T>(XElement element, string attributeName) { if (element == null) throw new ArgumentNullException("element");
if (String.IsNullOrEmpty(attributeName)) throw new ArgumentException("Cannot be null or empty", "attributeName");
XAttribute attribute = element.Attribute(attributeName); if (attribute == null) return default(T);
return FromString<T>(attribute.Value); } }
|
Here below is a test function.
void TestStringToType() { Console.WriteLine("String To int : {0}", StringToType.FromString<int>("32767")); TimeSpan timeSpan = new TimeSpan(2, 15, 45, 10, 10); DateTime dt = new DateTime(2010, 4, 16, 10, 24, 55); Console.WriteLine("String To DateTime : {0}", StringToType.FromString<DateTime>(dt.ToString()));
XElement xe = new XElement("Root", new XAttribute("price", 35)); Console.WriteLine("XElement : {0}", xe); Console.WriteLine("XElement attribute price : {0}", StringToType.FromXAttribute<int>(xe, "price"));
XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml("The Art of Data Structure"); XmlNode xn = xmlDoc.SelectSingleNode("/Books/Book"); Console.WriteLine("XmlNode : {0}", xn.OuterXml); Console.WriteLine("XmlNode attribute price : {0}", StringToType.FromXmlAttribute<double>(xn, "price")); }
|
阅读(431) | 评论(0) | 转发(0) |