我有许多不同大小和类型的类,我试图让一个通用脚本来填充它们。
请考虑以下代码。我遇到的问题是最后它只打印列名(正确)但没有值。
在单步执行代码时,我可以看到它认为我在 createDataRow 方法中传递的类型是空的,我不明白为什么。
public class tables { }
public class Dog : tables
{
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;
}
public static DataRow createDataRow(tables dog, DataTable touse) //This is half of the problem
{
Type type = dog.GetType();
DataRow x = touse.NewRow();
foreach (PropertyInfo prop in typeof(tables).GetProperties()) //this is the other half of the problem
{
x[prop.Name] = prop.GetValue(dog, null);
}
return x;
}
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(typeof(Dog));
DataRow dogRow = dogTable.NewRow();
dogRow = createDataRow(Killer, dogTable); //This is where I pass the data
dogTable.Rows.Add(dogRow);
foreach (DataRow row in dogTable.Rows)
{
foreach (DataColumn col in dogTable.Columns)
{
Console.WriteLine("Column {0} =" + row[col].ToString(),col.ColumnName);
}
}
Console.ReadLine();
}
}
现在,如果我要更改以下内容:
public static DataRow createDataRow(tables dog, DataTable touse)
到
public static DataRow createDataRow(Dog dog, DataTable touse)
和
foreach (PropertyInfo prop in typeof(tables).GetProperties())
到
foreach (PropertyInfo prop in typeof(Dog).GetProperties())
...一切正常。
但我不想这样做,因为这意味着我必须为我拥有数百个类的每个类创建一个“createDataRow”函数。
我究竟做错了什么?