如何根据字符串指定的类型将值转换为对应C#数据类型?
根据字符串类型名转换值的类型
你不能直接用字符串形式的类型名做强制转换,得先把字符串类型名转换成Type对象,再通过类型转换方法实现目标转换。以下是具体实现方案:
1. 建立内置类型映射表
C#的内置类型别名(如int、double)和CLR正式类型名(如System.Int32)不完全一致,所以先做一个映射表,把字符串类型名对应到正确的Type对象:
var typeMap = new Dictionary<string, Type> { {"int", typeof(int)}, {"double", typeof(double)}, {"string", typeof(string)}, {"bool", typeof(bool)}, {"float", typeof(float)} // 可按需扩展其他支持的类型 };
2. 封装转换方法
利用Convert.ChangeType完成值的类型转换,结合映射表封装成复用方法:
object ConvertValue(string typeName, string value) { if (!typeMap.TryGetValue(typeName.ToLower(), out var targetType)) { throw new ArgumentException($"不支持的类型:{typeName}"); } // 字符串类型直接返回原值 if (targetType == typeof(string)) { return value; } // 其他类型执行转换并处理格式异常 try { return Convert.ChangeType(value, targetType); } catch (FormatException) { throw new FormatException($"值 {value} 无法转换为 {typeName} 类型"); } }
3. 场景调用示例
结合你的需求调用方法:
string type; string value; // 示例1:int类型转换 type = "int"; value = "25"; dynamic result1 = ConvertValue(type, value); // result1为int类型,值25 // 示例2:double类型转换 type = "double"; value = "1.3"; dynamic result2 = ConvertValue(type, value); // result2为double类型,值1.3 // 示例3:string类型直接返回 type = "string"; value = "blablabla"; dynamic result3 = ConvertValue(type, value); // result3为string类型,值"blablabla"
补充说明
- 若需支持自定义类型,可在映射表中添加对应类型,并确保该类型实现了可从字符串转换的逻辑
- 异常处理可根据业务需求调整,比如返回默认值而非抛出异常
内容的提问来源于stack exchange,提问作者justSomeUser4
相关产品推荐
相关产品推荐

