简体   繁体   中英

C# string to necessary type conversion

I have following situation. Lets say i receive list of string values. I have to assign those values to specific type properties in Model. Model example:

    public int ID { get; set; }
    public DateTime? Date { get; set; }

There is no problem in type conversion as i get array of property types with System.reflection and use Convert.ChangeType(string value, type). However, i can't assignt Convert.ChangeType results to model properties because it returns object not my desired type of value. A short example of my problem:

string s1 = "1";
string s2= "11-JUN-2015";
PropertyInfo[] matDetailsProperties = Model.GetType().GetProperties();
List<Type> types = new List<Type>();
        foreach(var item in Model)
        {
            types.Add(item.PropertyType);
        }

Model.ID = Convert.ChangeType(s1, types[0]);
Model.Date = Convert.ChangeType(s2, types[1]);

This does not work as Convert.ChangeType returns object and i can't just use (dateTime)Convert.ChangeType(...), that's "dirty code" as i have model with 17 properties with different types. It would be perfect if i could use (Type[0])Convert.ChangeType(...) but it is not possible in C#

You could use reflection. How about something like this?

var prop = Model.GetType().GetProperty("ID");
var propValue = Convert.ChangeType(s1, types[0]);
if (prop != null && prop.CanWrite)
{
    prop.SetValue(Model, propValue, null);
}

You do not need to use Convert.ChangeType . Just use the existing parsers inside a function to create your model in a simple-to-follow fashion:

private static Model PopulateModel(IEnumerable<string> rawData)
{
    return new Model
    {
        ID = int.Parse(rawData[0]),
        Date = DateTime.Parse(rawData[1]),
        ...
    };
}

instead of Parse i'll suggest you use TryParse(string, out DateTime)

int tempId=default(int);
DateTime tempDate=DateTime.Min;

int.TryParse(s1,out tempId);
DateTime.TryParse(s2,out tempDate);

Model.ID = tempId;
Model.Date = tempDate;

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