2012-08-15 62 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