你有替代这些代码的方法吗,我想要一个更通用的代码 我试过转换类但没有成功
public object convert(Type type, string value)
{
object r = null;
if (type == typeof(bool))
{
r = bool.Parse(value);
}
else if (type == typeof(int))
{
r = int.Parse(value);
}
else if (type == typeof(string))
{
r = value;
}
return r;
}
最佳答案
var conv = TypeDescriptor.GetConverter(type);
return conv.ConvertFromInvariantString(value);
如果您不想“不变”,则存在其他转换操作。这取决于您的需要。如果您希望应用语言环境设置等,另请参阅 ConvertFromString
。
关于c# - 将字符串转换为类型实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9434025/