在上一个线程中,我询问了如何以通用方式从 id 获取注册表,我得到的答案是:
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);
}