获取传递给方法的对象的属性 c#
Get Properties of an Object Passed to a Method c#
我试图将一个对象传递给一个方法,然后将对象的属性与数据表中的列名匹配。我传递的对象是 "IndividualDetails." 类型 下面的代码运行良好,但是有没有一种方法可以更通用并传递任何类型的对象,而不必在代码中专门指定 "IndividualDetails" 类型.请查看 typeof() 行。
我希望能够将属性映射到多种类型对象的数据表的列。
提前感谢您的帮助。
List<IndividualDetails> individuals = new List<IndividualDetails>();
int[] index = ProcessX(ds.Tables["PersonsTable"], individuals);
private static int[] ProcessX(DataTable t, object p)
{
PropertyInfo[] Props = typeof(IndividualDetails).GetProperties(BindingFlags.Public | BindingFlags.Instance);
Console.WriteLine("PROPERTIES: "+p.GetType());
for (int x = 0; x < Props.GetLength(0); x++)
{
Console.WriteLine(Propsx[x].Name);
}
Console.ReadLine();
int[] pos = new int[t.Columns.Count];
for (int x = 0; x < t.Columns.Count; x++)
{
pos[x] = -1;
for (int i = 0; i < Props.Length; i++)
{
if (t.Columns[x].ColumnName.CompareTo(Props[i].Name) == 0)
{
pos[x] = i;
}
}
}
return pos;
}
如果我没看错你的代码,你应该可以这样做:
private static int[] ProcessX<T>(DataTable t, T obj)
{
PropertyInfo[] Props = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
您应该将其设为通用方法并使用类型引用提取属性。所以不是这个:
private static int[] ProcessX(DataTable t, object p)
{
PropertyInfo[] Props = typeof(IndividualDetails).GetProperties(BindingFlags.Public | BindingFlags.Instance);
这样做:
private static int[] ProcessX<T>(DataTable t, object p)
{
PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
我试图将一个对象传递给一个方法,然后将对象的属性与数据表中的列名匹配。我传递的对象是 "IndividualDetails." 类型 下面的代码运行良好,但是有没有一种方法可以更通用并传递任何类型的对象,而不必在代码中专门指定 "IndividualDetails" 类型.请查看 typeof() 行。
我希望能够将属性映射到多种类型对象的数据表的列。
提前感谢您的帮助。
List<IndividualDetails> individuals = new List<IndividualDetails>();
int[] index = ProcessX(ds.Tables["PersonsTable"], individuals);
private static int[] ProcessX(DataTable t, object p)
{
PropertyInfo[] Props = typeof(IndividualDetails).GetProperties(BindingFlags.Public | BindingFlags.Instance);
Console.WriteLine("PROPERTIES: "+p.GetType());
for (int x = 0; x < Props.GetLength(0); x++)
{
Console.WriteLine(Propsx[x].Name);
}
Console.ReadLine();
int[] pos = new int[t.Columns.Count];
for (int x = 0; x < t.Columns.Count; x++)
{
pos[x] = -1;
for (int i = 0; i < Props.Length; i++)
{
if (t.Columns[x].ColumnName.CompareTo(Props[i].Name) == 0)
{
pos[x] = i;
}
}
}
return pos;
}
如果我没看错你的代码,你应该可以这样做:
private static int[] ProcessX<T>(DataTable t, T obj)
{
PropertyInfo[] Props = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
您应该将其设为通用方法并使用类型引用提取属性。所以不是这个:
private static int[] ProcessX(DataTable t, object p)
{
PropertyInfo[] Props = typeof(IndividualDetails).GetProperties(BindingFlags.Public | BindingFlags.Instance);
这样做:
private static int[] ProcessX<T>(DataTable t, object p)
{
PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);