- /// <summary>
- /// 标题:使用类型转换器进行转换
- /// 作者:X.X.Y
- /// 日期:2009-07-30
- /// </summary>
- class Program
- {
- static void Main(string[] args)
- {
- // 使用类型转换器可以达到你的目的
- // 此处只做了转换,未做验证
- SingleDemo();
- Int32Demo();
- Console.ReadKey();
- }
- /// <summary>
- /// Single 转换示例
- /// </summary>
- public static void SingleDemo()
- {
- String fInput = "1.23456";
- Single fOutputFromTypeString = (System.Single)ConvertFromString("System.Single", fInput);
- Single fOutputFromType = (System.Single)ConvertFromString(typeof(System.Single), fInput);
- Single fOutputFromTypeConverter = (System.Single)ConvertFromString(new SingleConverter(), fInput);
- Console.WriteLine("--------------------------------------");
- Console.WriteLine("{0} Demo", "System.Single");
- Console.WriteLine("--------------------------------------");
- Console.WriteLine("OutputFromTypeString:{0}", fOutputFromTypeString);
- Console.WriteLine("OutputFromType:{0}", fOutputFromType);
- Console.WriteLine("OutputFromTypeConverter:{0}", fOutputFromTypeConverter);
- }
- /// <summary>
- /// Int32 转换示例
- /// </summary>
- public static void Int32Demo()
- {
- String fInput = "123456";
- Int32 fOutputFromTypeString = (System.Int32)ConvertFromString("System.Int32", fInput);
- Int32 fOutputFromType = (System.Int32)ConvertFromString(typeof(System.Int32), fInput);
- Int32 fOutputFromTypeConverter = (System.Int32)ConvertFromString(new Int32Converter(), fInput);
- Console.WriteLine("--------------------------------------");
- Console.WriteLine("{0} Demo", "System.Int32");
- Console.WriteLine("--------------------------------------");
- Console.WriteLine("OutputFromTypeString:{0}", fOutputFromTypeString);
- Console.WriteLine("OutputFromType:{0}", fOutputFromType);
- Console.WriteLine("OutputFromTypeConverter:{0}", fOutputFromTypeConverter);
- }
- /// <summary>
- /// 将指定文本转换为对象
- /// </summary>
- /// <param name="fTypeString">需要转换成的类型字符串</param>
- /// <param name="fInput">需要转换的文本</param>
- public static object ConvertFromString(String fTypeString, String fInput)
- {
- return ConvertFromString(Type.GetType(fTypeString), fInput);
- }
- /// <summary>
- /// 将指定文本转换为对象
- /// </summary>
- /// <param name="fType">需要转换成的类型</param>
- /// <param name="fInput">需要转换的文本</param>
- public static object ConvertFromString(Type fType, String fInput)
- {
- return ConvertFromString(TypeDescriptor.GetConverter(fType), fInput);
- }
- /// <summary>
- /// 将指定文本转换为对象
- /// </summary>
- /// <param name="fTypeConverter">转换器</param>
- /// <param name="fInput">需要转换的文本</param>
- public static object ConvertFromString(TypeConverter fTypeConverter, String fInput)
- {
- return fTypeConverter.ConvertFromString(fInput);
- }
- }