gpt4 book ai didi

c# - 如何将 DataRow 转换为对象

转载 作者:太空狗 更新时间:2023-10-29 18:02:37 25 4
gpt4 key购买 nike

我在我的项目中创建了一个 DataRow:

DataRow datarow;

我想将此 DataRow 转换为任何类型的对象。我该怎么做?

最佳答案

这是我使用它的一种非常酷的方式。

    public static T ToObject<T>(this DataRow dataRow)
where T : new()
{
T item = new T();

foreach (DataColumn column in dataRow.Table.Columns)
{
PropertyInfo property = GetProperty(typeof(T), column.ColumnName);

if (property != null && dataRow[column] != DBNull.Value && dataRow[column].ToString() != "NULL")
{
property.SetValue(item, ChangeType(dataRow[column], property.PropertyType), null);
}
}

return item;
}

private static PropertyInfo GetProperty(Type type, string attributeName)
{
PropertyInfo property = type.GetProperty(attributeName);

if (property != null)
{
return property;
}

return type.GetProperties()
.Where(p => p.IsDefined(typeof(DisplayAttribute), false) && p.GetCustomAttributes(typeof(DisplayAttribute), false).Cast<DisplayAttribute>().Single().Name == attributeName)
.FirstOrDefault();
}

public static object ChangeType(object value, Type type)
{
if (type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
{
if (value == null)
{
return null;
}

return Convert.ChangeType(value, Nullable.GetUnderlyingType(type));
}

return Convert.ChangeType(value, type);
}

关于c# - 如何将 DataRow 转换为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19673502/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com