据我所知,至少有3种方法可以在.NET中转换数据类型:
使用System.ComponentModel.TypeConverter
var conv = System.ComponentModel.TypeDescriptor.GetConverter(typeof(int));
var i1 = (int)conv.ConvertFrom("123");
Run Code Online (Sandbox Code Playgroud)
使用System.Convert.ChangeType():
var i2 = (int) Convert.ChangeType("123", typeof (int));
Run Code Online (Sandbox Code Playgroud)
使用目标类型的Parse/TryParse方法:
var i3 = int.Parse("123"); // or TryParse
Run Code Online (Sandbox Code Playgroud)
是否有任何指导方针或经验法则何时使用哪种方法在.NET基础数据类型之间进行转换(特别是从字符串到其他数据类型)?
这是关于使用反射转换值的问题的后续行动.将某种类型的对象转换为另一种类型可以这样做:
object convertedValue = Convert.ChangeType(value, targetType);
Run Code Online (Sandbox Code Playgroud)
给定两个Type实例(比如FromType和ToType),有没有办法测试转换是否成功?
我可以写一个像这样的扩展方法:
public static class TypeExtensions
{
public static bool CanChangeType(this Type fromType, Type toType)
{
// what to put here?
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:这就是我现在所拥有的.丑陋,但我还没有看到另一种方式......
bool CanChangeType(Type sourceType, Type targetType)
{
try
{
var instanceOfSourceType = Activator.CreateInstance(sourceType);
Convert.ChangeType(instanceOfSourceType, targetType);
return true; // OK, it can be converted
}
catch (Exception ex)
{
return false;
}
Run Code Online (Sandbox Code Playgroud)