已知数据的Type和字符串表示的值反射获取对象

发布时间 2023-11-06 18:40:50作者: 六镇2012

转自Convert string to object (c#)_c# string转object-CSDN博客

 

需求:已知数据的Type和string表示的值,据此两个条件生成真正的值,例如Type为System.Boolean,值为false

Type myType = Type.GetType("System.Boolean");
 
var result= Convert.ChangeType("false", myType);

以上仅限基础类型,附上基础类型列表,全类型名待补充

/// <summary>
/// 基础类型列表
/// </summary>
public static List<string> BaseType = new List<string>()
{
    "bool",
    "byte",
    "sbyte",
    "char",
    "short",
    "ushort",
    "int",
    "uint",
    "long",
    "ulong",
    "float",
    "double",
    "decimal",
    "string"
};