通用类型转换方法(.Net)

我正在尝试创建一个通用的方法来投射一个对象,但似乎无法破解那个栗子。 (现在是星期五下午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; 

如何在不创建无数if-else-staments的情况下一般地投射该对象?

如果您使用的类型实现了IConvertible (所有基本类型都可以),则可以使用Convert.ChangeType方法。

  Convert.ChangeType(value, targetType); 

看看Convert.ChangeType方法,我认为它将满足您的需求。

您无法将其强制转换为动态指定的类型。

您可以考虑使用generics ,但我需要更多代码才能看到它如何帮助您。

您可以执行以下操作:

  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的改变类型function