我刚学习了泛型,想知道是否可以使用它来从我的类动态构建数据表。
或者我可能理解有误。这是我的代码,我想做的是从我的现有类创建一个数据表并填充它。然而我的思路卡住了。
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 类来填充数据?
错误3:参数1:无法将'Generics.Dog'转换为'System.Type'
错误1:'Generics.Dog'是一个'type',但像一个'variable'使用 - vwdewaal