获取传递给方法的对象的属性c#

时间:2015-09-13 02:48:48

标签: c# object properties

我正在尝试将对象传递给方法,然后将对象的属性与数据表中的列名匹配。我传递的对象是“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;

    }

2 个答案:

答案 0 :(得分:1)

如果我正确地阅读您的代码,您应该能够这样做:

private static int[] ProcessX<T>(DataTable t, T obj)
    {

        PropertyInfo[] Props = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);

答案 1 :(得分:0)

您应该将此作为通用方法,并使用Type引用来提取属性。所以不要这样:

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);
相关问题