How to convert from string to object of any type?

喜欢而已 提交于 2019-12-25 18:38:52

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!