Sai*_*aid 3 c# type-conversion
你有这些代码的替代品,我想要一个更通用的代码我尝试转换类但没有成功
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;
}
Run Code Online (Sandbox Code Playgroud)
var conv = TypeDescriptor.GetConverter(type);
return conv.ConvertFromInvariantString(value);
Run Code Online (Sandbox Code Playgroud)
如果您不想要"不变",则存在其他转换操作.这取决于您的需求.另请参阅ConvertFromString是否要将区域设置设置为适用等.