如何查找存储在字符串中的数据类型的类型

时间:2019-04-08 11:49:29

标签: c# reflection

我从wsdl中提取了输入和输出参数,并存储在字符串中。 示例:字符串type=parameterType。 输出:type="int"

现在,我要获取此类型的默认值(在本例中为int)。

我已经尝试过:type.GetType()。结果是String类的类型,但是,我想要该值的类型。

这样我就可以获取实际值类型的默认值,而不是字符串的默认值,例如int ==> 0,而不是"int" ==> string ==> null

2 个答案:

答案 0 :(得分:0)

如果格式始终相同(第一个类型然后为值),则可以使用String.Split将类型提取为字符串,然后可以执行if(typeString == "int")然后从字符串转换为int int x = int.Parse(valueString);,希望给你一个想法。

答案 1 :(得分:0)

Given the name of the type, you need to use reflection to find the actual type, then get its default value. However, since the type name for int is System.Int32, you'll need to go through a dictionary, e.g.:

var dictionary = new Dictionary<string, string>
{
    {"int", "System.Int32"},
};

var typeName = "int";
if (dictionary.ContainsKey(typeName))
    typeName = dictionary[typeName];
var type = Type.GetType(typeName);

var defaultValue = type.IsValueType ? Activator.CreateInstance(type) : null;