gpt4 book ai didi

c# - 有没有办法声明一个类似 Linq 的 CustomWhere() 方法并在没有冗余项的情况下调用它?

转载 作者:行者123 更新时间:2023-12-04 08:01:07 24 4
gpt4 key购买 nike

我们有一个项目使用了 EntityFramework 无法使用的旧数据库。
所以我们已经开始构建一个穷人的 EntityFramework,它有一个基类 CustomBaseTable从哪个实体类派生。另一个类(class),CustomQueryBuilder , 具有构建 SQL 查询的方法:BuildSelectQuery(CustomBaseTable p_objEntity)等等。
我们的第一个版本很好地构建了查询,但是我们使用了相当粗糙的对象,这些对象不是很灵活(为了节省空间而保留细节)。
我最近意识到使用 Expression对象将更加高效和灵活。
所以我想给 CustomBaseTable 添加一个方法,这或多或少会像 Where() 一样工作:

    EntityTable z_objEntity = new EntityTable();
z_objEntity.CustomWhere(t => t.Field1 == Value1);
CustomQueryBuilder z_objBuilder = new CustomQueryBuilder(DBTypeEnum.DataBaseType);
string z_strQuery = z_objBuilder.BuildSelectQuery(z_objEntity);
现在,我在声明 CustomWhere() 时遇到了障碍。 .我尝试了几种方法:
    public class CustomBaseTable
{
public void CustomWhere1<T>(Expression<Func<T, bool>> p_expWhereClause) where T : CustomBaseTable
public void CustomWhere2<T>(this T z_objTable, Expression<Func<T, bool>> p_expWhereClause) where T : CustomBaseTable
}

public static class CustomBaseTableExtension
{
public static void CustomWhere3<T>(this T z_objTable, Expression<Func<T, bool>> p_expWhereClause) where T : CustomBaseTable
}

但是,就我而言,每个人都有一个缺陷:
  • CustomWhere1需要指定 <EntityTable>每次调用都会占用空间并且是多余的,因为调用该方法的对象具有相同的类型:z_objEntity.CustomWhere<EntityTable>(t => t.Field1 == Value1);
  • CustomWhere2需要传递它所调用的对象,也占用空间并且也是多余的:z_objEntity.CustomWhere(z_objEntity, t => t.Field1 == Value1);
  • CustomWhere3巧妙地避免了这两个缺陷,但显然需要创建一个单独的扩展类。如果需要,我会使用它,但我不明白为什么需要它。

  • 有没有办法在不创建扩展类的情况下使用这种简单的调用语法?

    最佳答案

    是的。您可以使用 curiously recurring template pattern , 定义 EntityTable : CustomBaseTable<EntityTable> ,因此,有 EntityTable可用作通用参数。这是一个最小的例子( fiddle ):

    using System;
    using System.Linq.Expressions;

    public class Program
    {
    public static void Main()
    {
    var Value1 = "value1";
    var z_objEntity = new EntityTable();

    z_objEntity.CustomWhere1(t => t.Field1 == Value1); // compiles!
    }

    public class CustomBaseTable<T>
    {
    public void CustomWhere1(Expression<Func<T, bool>> p_expWhereClause)
    {
    throw new NotImplementedException();
    }
    }

    public class EntityTable : CustomBaseTable<EntityTable>
    {
    public string Field1 { get; set; }
    }
    }
    话虽如此,我确实相信扩展类是解决您问题的最简单方法。

    CustomWhere3 neatly avoid both flaws, but apparently requires creating a separate extension class. I'll go with it if I need to, but I fail to see why it's needed.


    需要它,因为你
  • 想在你的基类中定义 CustomWhere,
  • CustomWhere 有一个参数,其类型取决于具体的派生类,和
  • C#(还)没有 "this" type .

  • 因此,我们要么需要
  • 使派生类可用于基类(这是我的答案中的代码所做的)或
  • 在其他地方定义 CustomWhere(这是您的扩展方法示例 CustomWhere3 所做的)。
  • 关于c# - 有没有办法声明一个类似 Linq 的 CustomWhere() 方法并在没有冗余项的情况下调用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66461781/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com