繁体   English   中英

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

[英]C# string to necessary type conversion

我有以下情况。 可以说我收到字符串值列表。 我必须将这些值分配给Model中的特定类型属性。 型号示例:

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

类型转换没有问题,因为我使用System.reflection获取属性类型数组并使用Convert.ChangeType(string value,type)。 但是,我无法将Convert.ChangeType结果分配给模型属性,因为它返回的对象不是我想要的值类型。 我的问题的简短示例:

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]);

这不起作用,因为Convert.ChangeType返回对象,并且我不能仅使用(dateTime)Convert.ChangeType(...),这是“脏代码”,因为我具有带有17种具有不同类型的属性的模型。 如果我可以使用(Type [0])Convert.ChangeType(...),那将是完美的,但是在C#中是不可能的

您可以使用反射。 这样的事情怎么样?

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

您不需要使用Convert.ChangeType 只需使用函数中现有的解析器以简单易懂的方式创建模型:

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

而不是解析,我建议您使用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