changetype

Why does Convert.ChangeType take an object parameter?

你说的曾经没有我的故事 提交于 2019-12-04 03:22:50
问题 The Convert class has been in existence since .NET 1.0. The IConvertible interface has also existed since this time. The Convert.ChangeType method only works on objects of types that implement IConvertible (in fact, unless I'm mistaken, all of the conversion methods provided by the Convert class are this way). So why is the parameter type object ? In other words, instead of this: public object ChangeType(object value, Type conversionType); Why isn't the signature this? public object

Convert.ChangeType and converting to enums?

瘦欲@ 提交于 2019-11-30 16:46:21
I got an Int16 value, from the database, and need to convert this to an enum type. This is unfortunately done in a layer of the code that knows very little about the objects except for what it can gather through reflection. As such, it ends up calling Convert.ChangeType which fails with an invalid cast exception. I found what I consider a smelly workaround, like this: String name = Enum.GetName(destinationType, value); Object enumValue = Enum.Parse(destinationType, name, false); Is there a better way, so that I don't have to move through this String operation? Here's a short, but complete,

Convert.ChangeType and converting to enums?

三世轮回 提交于 2019-11-30 16:20:36
问题 I got an Int16 value, from the database, and need to convert this to an enum type. This is unfortunately done in a layer of the code that knows very little about the objects except for what it can gather through reflection. As such, it ends up calling Convert.ChangeType which fails with an invalid cast exception. I found what I consider a smelly workaround, like this: String name = Enum.GetName(destinationType, value); Object enumValue = Enum.Parse(destinationType, name, false); Is there a