gpt4 book ai didi

c# - 使用反射从类创建数据表?

转载 作者:IT王子 更新时间:2023-10-29 04:17:18 24 4
gpt4 key购买 nike

我刚刚了解了泛型,我想知道我是否可以使用它从我的类中动态构建数据表。

或者我可能忽略了这里的重点。这是我的代码,我要做的是从我现有的类创建一个数据表并填充它。然而,我陷入了思考过程。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Data;

namespace Generics
{
public class Dog
{
public string Breed { get; set; }
public string Name { get; set; }
public int legs { get; set; }
public bool tail { get; set; }
}

class Program
{
public static DataTable CreateDataTable(Type animaltype)
{
DataTable return_Datatable = new DataTable();
foreach (PropertyInfo info in animaltype.GetProperties())
{
return_Datatable.Columns.Add(new DataColumn(info.Name, info.PropertyType));
}
return return_Datatable;
}

static void Main(string[] args)
{
Dog Killer = new Dog();
Killer.Breed = "Maltese Poodle";
Killer.legs = 3;
Killer.tail = false;
Killer.Name = "Killer";

DataTable dogTable = new DataTable();
dogTable = CreateDataTable(Dog);
//How do I continue from here?


}
}
}

现在在 DataTable 点它出错了。另外,作为反射和泛型的新手,我将如何使用 Killer 类实际填充数据?

最佳答案

在之前所有答案的基础上,这里有一个从任何集合创建 DataTable 的版本:

public static DataTable CreateDataTable<T>(IEnumerable<T> list)
{
Type type = typeof(T);
var properties = type.GetProperties();

DataTable dataTable = new DataTable();
dataTable.TableName = typeof(T).FullName;
foreach (PropertyInfo info in properties)
{
dataTable.Columns.Add(new DataColumn(info.Name, Nullable.GetUnderlyingType(info.PropertyType) ?? info.PropertyType));
}

foreach (T entity in list)
{
object[] values = new object[properties.Length];
for (int i = 0; i < properties.Length; i++)
{
values[i] = properties[i].GetValue(entity);
}

dataTable.Rows.Add(values);
}

return dataTable;
}

关于c# - 使用反射从类创建数据表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18746064/

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