代码之家  ›  专栏  ›  技术社区  ›  Faizan S.

按db4o中的类型查询

  •  4
  • Faizan S.  · 技术社区  · 16 年前

    如何将类类型传递到C中的函数中?

    当我进入db4o和c时,我在阅读教程后编写了以下函数:

        public static void PrintAllPilots("CLASS HERE", string pathToDb)
        {
            IObjectContainer db = Db4oFactory.OpenFile(pathToDb);
            IObjectSet result = db.QueryByExample(typeof("CLASS HERE"));
            db.Close();
            ListResult(result);
        }
    
    4 回复  |  直到 16 年前
        1
  •  11
  •   JaredPar    16 年前

    有两种方法。第一种方法是显式使用类型类型。

    public static void PrintAllPilots(Type type, string pathToDb)
    {
      ...
      IObjectSet result = db.QueryByExample(type);
    }
    
    PrintAllPilots(typeof(SomeType),somePath);
    

    第二种是使用仿制药

    public static void PrintAllPilots<T>(string pathToDb)
    {
      ...
      IObjectSet result = db.QueryByExample(typeof(T));
    }
    
    PrintAllPilots<SomeType>(somePath);
    
        2
  •  5
  •   Judah Gabriel Himango    16 年前

    jon、jared和yshuditelu给出的答案使用示例查询,这是一种基本上不用的db4o查询机制,将来可能会被弃用。

    在db4o上查询.NET的首选方法是本机查询和LINQ。

    // Query for all Pilots using DB4O native query:
    var result = db.Query<Pilot>();
    

    或者使用linq-to-db4o:

    // Query for all Pilots using LINQ
    var result = from Pilot p in db
                 select p;
    

    这两项工作都要求您在编译时知道类型(例如pilot)。如果您在编译时不知道类型,则可以使用db4o soda查询:

    var query = db.Query();
    query.Constrain(someObj.GetType());
    var results = query.Execute();
    

    编辑 为什么要使用linq而不是soda、按示例查询(qbe)或本机查询(nq)?因为Linq使查询表达式变得非常自然。例如,您可以通过以下方式查询名为Michael的飞行员:

    var michaelPilots = from Pilot p in db
                        where p.Name == "Michael"
                        select p;
    

    Linq是可组合的,这意味着你可以这样做:

    var first20MichaelPilots = michaelPilots.Take(20);
    

    当您迭代结果时,仍然可以在db4o中执行一个有效的查询。在苏打水、QBE或NQ中做同样的事情充其量是丑陋的。

        3
  •  1
  •   Timothy Carter    16 年前

    我想这就是你想要的:

    public static void PrintAllPilots(Type classType, string pathToDb)
    {
        IObjectContainer db = Db4oFactory.OpenFile(pathToDb);
        IObjectSet result = db.QueryByExample(classType);
        db.Close();
        ListResult(result);
    }
    
        4
  •  0
  •   Jon Limjap    16 年前

    您可以使用 Type :

    public static void PrintAllPilots(Type type, string pathToDb)
    

    或者可以使用泛型推断类型:

    public static void PrintAllPilots<T>(string pathToDb)
    {
       //...
       var result = db.QueryByExample(typeof(T));
    }