【问题标题】:Make a LINQ query on object implementing interface对对象实现接口进行 LINQ 查询
【发布时间】:2011-01-20 06:40:33
【问题描述】:

请参阅下面的代码。我想检查一些属性(例如在 IsActive 上)。你能告诉我在我的情况下如何在 GetList() 中实现它吗?

谢谢,

   public interface ILookup
    {
        int Id { get; set; }
        string FR { get; set; }
        string NL { get; set; }
        string EN { get; set; }
        bool IsActive { get; set; }
    }

    public class LookupA : ILookup
    {

    }
    public class LookupB : ILookup
    {

    }

    public interface ILookupRepository<T>
    {
        IList<T> GetList();
    }


    public class LookupRepository<T> : ILookupRepository<T>
    {
        public IList<T> GetList()
        {
            List<T> list = Session.Query<T>().ToList<T>();
            return list;
        }       
    }

【问题讨论】:

    标签: c# .net linq generics


    【解决方案1】:

    如果你知道T 将是ILookup 类型,你需要像这样对其进行约束:

    public interface ILookup
    {
        int Id { get; set; }
        string FR { get; set; }
        string NL { get; set; }
        string EN { get; set; }
        bool IsActive { get; set; }
    }
    
    public class LookupA : ILookup
    {
    
    }
    public class LookupB : ILookup
    {
    
    }
    
    public interface ILookupRepository<T>
    {
        IList<T> GetList();
    }
    
    
    public class LookupRepository<T> : ILookupRepository<T> where T : ILookup
    {
        public IList<T> GetList()
        {
            List<T> list = Session.Query<T>().Where(y => y.IsActive).ToList<T>();
            return list;
        }       
    }
    

    【讨论】:

    • 该死,秒杀我 ;p 旁白:在我的代码中,ILookupRepository&lt;T&gt; 上还有 where T : ILookup,因为听起来它总是与 ILookup 一起使用——也许是 OP 的一个思考……
    • 我对@9​​87654327@ 也有限制,但将其删除。原因是我没有理由将ILookupRepository 限制为一种类型,尽管interface 的名称暗示了这一点。我不会过度约束自己。
    • 想象一下,我想添加我想要返回值的字段名称作为参数,例如:GetById(myIdValue, thefield),该字段的值为 EN、FR 或 NL
    • 如果您没有那么多参数,我会对其进行硬编码以提高性能。但是如果你有超过 EN、FR 和 NL 我会使用反射。您的字符串是某种翻译查找吗?如果是这种情况,我会使用某种字典,而不是每种语言都有一个变量。
    【解决方案2】:

    您应该能够利用 Generic Constraints 来帮助您。

    首先,改变你的接口定义:

    public interface ILookupRepository<T> where T : ILookup
    //                                    ^^^^^^^^^^^^^^^^^
    

    其次,更改您的类定义以匹配约束:

    public class LookupRepository<T> : ILookupRepository<T> where T : ILookup
    //                                                      ^^^^^^^^^^^^^^^^^
    

    约束将需要泛型类型参数来实现ILookup。这将允许您在 GetList 方法中使用接口成员。

    【讨论】:

    • 他不需要ILookupRepository 的约束来让他的东西正常工作。阅读我对我的回答的评论,为什么我认为没有必要。
    猜你喜欢
    • 1970-01-01
    • 2015-07-03
    • 2011-03-06
    • 1970-01-01
    • 2011-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多