如何将类类型传递给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);
    }
有帮助吗?

解决方案

有两种方法。第一种是明确使用Type类型。

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);

其他提示

Jon,Jared和yshuditelu给出的答案使用了一个很大程度上未使用的DB4o查询机制的查询示例,并且可能在将来被弃用。

查询DB4O for .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使得查询表达式非常自然。例如,以下是您如何查询名为迈克尔的飞行员:

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

LINQ是可组合的,这意味着你可以做这样的事情:

var first20MichaelPilots = michaelPilots.Take(20);

当你迭代结果时,你仍然可以在DB4O中执行有效的查询。在SODA或QBE或NQ中做同样的事情是最难的。

我认为这就是你想要的:

public static void PrintAllPilots(Type classType, string pathToDb)
{
    IObjectContainer db = Db4oFactory.OpenFile(pathToDb);
    IObjectSet result = db.QueryByExample(classType);
    db.Close();
    ListResult(result);
}

您可以使用 Type

手动完成
public static void PrintAllPilots(Type type, string pathToDb)

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

public static void PrintAllPilots<T>(string pathToDb)
{
   //...
   var result = db.QueryByExample(typeof(T));
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top