将对象转换为其他数据类型的通用方法

本文关键字:方法 数据类型 其他 对象 转换 | 更新日期: 2023-09-27 18:34:45

我有几行,我清楚地说我想将某些东西转换为stringbooldate等。

是否可以以某种方式将其封装在我传递要转换的对象并传递我想要获得的回报的方法中?

我现在拥有的

foreach (var item in archive.Items)
{
    var newItem = new Item();
    newItem.Notes = Convert.ToString(item.FirstOrDefault(x => x.Key == "notes").Value);
    newItem.IsPublic = Convert.ToBoolean(item.FirstOrDefault(x => x.Key == "ispublic").Value);
}

我想要什么(伪(

foreach (var item in archive.Items)
{
    var newItem = new Item();
    newItem.Notes = GetValue("notes", string)
    newItem.IsPublic = GetValue("ispublic", bool)
}
// ...
public T GetValue(string key, T type)
{
    return object.FirstOrDefault(x => x.Key == key).Value; // Convert this object to T and return?
}

这样的事情可能吗?

将对象转换为其他数据类型的通用方法

你需要

围绕Convert.ChangeType()编写一个通用包装器:

public T GetValue<T>(string key) {
    return (T)Convert.ChangeType(..., typeof(T));
}
public T GetValue<T>(string key, T type)
{
    return Convert.ChangeType(object.FirstOrDefault(x => x.Key == key).Value, typeof(T));
}