问题
I need to convert from a string that contains data to an object of some type that is passed using reflection. I have a not-serializable object that contains properties of any type, and I want to load data to that object.
For example, that object has a property, Color BgColor. When I am trying to set "Red" value to that property, I get that conversion is not possible from string to Color. I need general code.
回答1:
Try Convert.ChangeType for general conversions.
But in your case I think the Color.FromName method would be best:
Creates a Color structure from the specified name of a predefined color.
回答2:
If all you need to do is convert a string to its value in an enum, you can use code similar to the following:
public static T ToEnum<T>(this string original)
{
Array values = Enum.GetValues(typeof(T));
foreach (T value in values)
{
if (value.ToString().ToUpperInvariant() == original.ToUpperInvariant())
return value;
}
throw new NotFoundException();
}
If you need to convert other types, then perhaps specifying types and the formats of the string might help people direct you better.
来源:https://stackoverflow.com/questions/1498091/how-to-convert-from-string-to-object-of-any-type