是否可以使用反射从通用实体访问属性(按名称)?

时间:2012-01-24 14:09:46

标签: c# generics reflection

我想从泛型类T创建一个通用查询。有没有办法通过反射或其他东西来做类似的东西?

public class DAO<T>        
    where T : class
{
    protected ObjectSet<T> Entities
    {
        get
        {
            return myContextThatIsInSomewhere.CreateObjectSet<T>();
        }
    }

    public IList<T> SelectBy(object fields)
    {
        if (fields == null)
        {
            throw new ArgumentNullException("fields");
        }

        var query = from e in this.Entities                    
                    select e;

        foreach (var field in fields.GetType().GetFields())
        {
            query = from e in this.Entities
                    // Do something like that:                   
                    where e.(field.Name) == field.GetValue()
                    select e;         
        }

        return query.ToList();
    }
}

1 个答案:

答案 0 :(得分:3)

SelectByExpression<Func<T, bool>>(称之为predicate)然后你就可以说

var query = this.Entities.Where(predicate);

您可以通过说

传递Expression<Func<T, bool>>的实例
x => x.Foo == foo

例如。