简体   繁体   中英

Converting strings to Object types in runtime

I have a class, something simple like

class Example
{
    uint id;
    ushort value1;
    string value2;
    DateTime timestamp;
 }

I also have a csv, like:

id;value1;value2;timestamp
5;0x2313;whatever;2012-12-23-12:14:34,567
6;0x2A14;something;2012-12-24:13:14:15:167

I would like to create objects based on the CSV, however the real class is a lot bigger and prone to change, so I would like to use reflection. I have some code getting the names of Properties and finding the corresponding string. What I don't get is, how I can convert the string to whatever type the Property is. I have found some code samples how to CAST the values, but casting a string to short is not what looks like a solution.

Any ideas?

您可以使用Convert.ChangeType方法:

myObject.Field = Convert.ChangeType(value, fieldType);

You may want to look at the Convert class. If you know the type to which you want to convert the string, you can use that.

Or, you can use the type's Parse() or TryParse() methods.

For example, to convert a string to a short you can use Int16.TryParse()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM