相关疑难解决方法(0)

TypeConverter vs. Convert vs. TargetType.Parse

据我所知,至少有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基础数据类型之间进行转换(特别是从字符串到其他数据类型)?

.net c# type-conversion

39
推荐指数
2
解决办法
1万
查看次数

测试Convert.ChangeType是否适用于两种类型

这是关于使用反射转换值的问题的后续行动.将某种类型的对象转换为另一种类型可以这样做:

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)

c# reflection

27
推荐指数
2
解决办法
2万
查看次数

无法在.NET中捕获的异常列表

什么是例外列表CAN NOT在.NET中被抓?或者我在哪里可以找到这样的清单?

.net c# vb.net

17
推荐指数
3
解决办法
7986
查看次数

标签 统计

c# ×3

.net ×2

reflection ×1

type-conversion ×1

vb.net ×1