2019-8-31-C#-转换类型和字符串

title author date CreateTime categories
C# 转换类型和字符串
lindexi
2019-08-31 16:55:58 +0800
2018-2-13 17:23:3 +0800
C#

有时候我们需要互转类型和字符串,把字符串转类型、把类型转字符串。

如果是基础类型,可以使用 x.Parse 这个方法,很多基础类型都支持。

那么我们可以使用 TypeDescriptor

            string value = "123";
            var typeDescriptor = TypeDescriptor.GetConverter(typeof(int));
            int @int =(int) typeDescriptor.ConvertFromString(value);
            Console.WriteLine(typeDescriptor.ConvertToString(@int));
            typeDescriptor = TypeDescriptor.GetConverter(typeof(double));
            double @double = (double)typeDescriptor.ConvertFromString(value);
            Console.WriteLine(typeDescriptor.ConvertToString(@double));

参见:http://www.jianshu.com/p/cdc8f5fe6405

原文地址:https://www.cnblogs.com/lindexi/p/12086247.html