2012-08-15 63 views
0

從以前thread我問怎麼從一個通用的方法的ID獲得註冊,我得到的答案是這樣的:c# - 我怎樣才能從一個實例泛型類的屬性?

public class DBAccess 
{ 
    public virtual DataBaseTable GetById<DataBaseTable>(int id, Table<DataBaseTable> table) where DataBaseTable : class 
    { 
     var itemParameter = Expression.Parameter(typeof(DataBaseTable), "item"); 
     var whereExpression = Expression.Lambda<Func<DataBaseTable, bool>> 
      (
      Expression.Equal(
       Expression.Property(
        itemParameter, 
        "Id" 
        ), 
       Expression.Constant(id) 
       ), 
      new[] { itemParameter } 
      ); 
     return table.Where(whereExpression).Single(); 
    } 
} 

其中一期工程不錯,但現在我卡住了,不知道怎麼弄任何它的屬性,給出一個具體的問題,我怎麼能讓這個函數在下面的工作?

public static int GetRelatedTableId<DataBaseTable> 
    (Table<DataBaseTable> table,String RelatedTableId) where DataBaseTable : class 
    { 
     DBAccess RegistryGet = new DBAccess();  
     DataBaseTable tab = RegistryGet.GetById<DataBaseTable>(id, table); 
     return tab.getAttributeByString(RelatedTableId);//i just made this up 
    } 

更新解決方案

由於下面我的鏈接設法解決這個

public static int GetRelatedTableId<DataBaseTable> 
    (Table<DataBaseTable> table,String RelatedTableId) where DataBaseTable : class 
    { 
     DBAccess RegistryGet = new DBAccess();  
     DataBaseTable tab = RegistryGet.GetById<DataBaseTable>(id, table); 
     return (int)(tab.GetType().GetProperty(RelatedTableId)).GetValue(tab, null); 
    } 

回答

0

如果你的屬性名稱在運行時才知道,那麼你可以使用反射來檢查鍵入DataBaseTable,按名稱查找感興趣的屬性,然後從您的實例tab中檢索其值。

看到這個問題的答案爲例:How can I get the value of a string property via Reflection?

澄清:是的,你的類型是一個通用的說法,但typeof(DataBaseTable)tab.GetType()仍然可以讓你檢查所使用的特定類型。

+0

的感謝!這引導我回答 – Mol 2012-08-15 03:41:08

0

如果您在運行時只知道屬性名稱,請使用反射...雖然這是一種代碼味道往往不是。

如果在編譯時(並且正在使用.net 4)知道屬性名稱而不是具體類型,則將返回值轉換爲dynamic並正常訪問該屬性。

如果您知道編譯時的具體類型和屬性,將返回值轉換爲返回的類型並正常訪問屬性。

還根據所提供的片段你的代碼也許應該或者是

public class DBAccess<T> where T : class 
{ 
    public virtual T GetById(int id, Table<T> table) 
    { 

public static class DBAccess 
{ 
    public static T GetById<T>(int id, Table<T> table) where T : class 
    { 
+0

是的,你是對的,我改變了這個問題,謝謝! – Mol 2012-08-15 02:55:46

+0

我不同意使用反射是一種代碼味道往往不是。您可以在許多廣泛使用和深思熟慮的庫中找到反射。這是一個像其他任何工具。 – 2012-08-15 15:25:15