简体   繁体   English

C#字符串到必要的类型转换

[英]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中的特定类型属性。 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). 类型转换没有问题,因为我使用System.reflection获取属性类型数组并使用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. 但是,我无法将Convert.ChangeType结果分配给模型属性,因为它返回的对象不是我想要的值类型。 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. 这不起作用,因为Convert.ChangeType返回对象,并且我不能仅使用(dateTime)Convert.ChangeType(...),这是“脏代码”,因为我具有带有17种具有不同类型的属性的模型。 It would be perfect if i could use (Type[0])Convert.ChangeType(...) but it is not possible in C# 如果我可以使用(Type [0])Convert.ChangeType(...),那将是完美的,但是在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 . 您不需要使用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) 而不是解析,我建议您使用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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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