[英]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);
您應該將此方法設為通用方法,並使用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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.