代码之家  ›  专栏  ›  技术社区  ›  André Haupt saber safavi

泛型类型转换方法(.Net)

  •  11
  • André Haupt saber safavi  · 技术社区  · 16 年前

    我正在尝试创建一个通用方法来投射对象,但似乎无法解决这个问题。(现在是周五下午3点,这是漫长的一周)

    好的,我有一个场景:

    // We have a value (which .net sets as a double by default)
    object obj = 1.0;
    
    // We have the target type as a string, which could be anything:
    // say string sometType = "System.Decimal"
    Type type = Type.GetType(someType);
    
    // I need a generic way of casting this
    object castedObj = (xxx) obj;
    

    4 回复  |  直到 16 年前
        1
  •  18
  •   Pop Catalin    16 年前

    你可以用 Convert.ChangeType 方法,如果使用的类型实现 IConvertible

        Convert.ChangeType(value, targetType);
    
        2
  •  3
  •   Jamie Ide    16 年前

    看一看这本书 Convert.ChangeType

        3
  •  0
  •   pgb    16 年前

    不能将其强制转换为动态指定的类型。

    你可以考虑使用 generics

        4
  •  0
  •   Mark Coleman    16 年前

    您可以执行以下操作:

        Type underlyingType = Type.GetType(someType);
    
    
        if (underlyingType.IsGenericType && underlyingType.GetGenericTypeDefinition().Equals(typeof (Nullable<>)))
        {
            var converter = new NullableConverter(underlyingType);
            underlyingType = converter.UnderlyingType;
        }
    
        // Try changing to Guid  
        if (underlyingType == typeof (Guid))
        {
            return new Guid(value.ToString());
        }
        return Convert.ChangeType(value, underlyingType);
    

    荣誉 Monsters Go My.net 对于更改类型函数