如何从一种方法引用另一种方法中的 'var'?

How to reference a 'var' from one method in another?

我知道 var 仅在其方法的范围内。但是我遇到了这样一种情况,即来自数据库连接方法的集合 'var' 需要在后续的 Query() 方法中访问才能进行查询。

具体错误为:The name collection doesn't exist in the current context

我一直在引用 MongoDB C# driver docs 来设置连接和查询,除了这个问题之外,其他一切似乎都是正确的。

有谁知道如何重构我的代码来解决错误?

我的两个方法在 OrderRespository class 中指定如下,它建立数据库连接和查询:

//Method to create MongoDB Orders connection and get handle on collections
    public static bool CreateConnection()
    {

        var client = new MongoClient(connectionString);

        try
        {
          var database = client.GetDatabase("orders");
          //Get a handle on the customers collection:
          var collection = database.GetCollection<BsonDocument>("customers");
        }
        catch(MongoConnectionException)
        { 
            return false; 
        } 

        return true; 
    }



    //Method to test query on database documents
    public async static Task<List<Customer>> FindCustomers()
    {
        var documents =  await collection.Find(new BsonDocument()).ToListAsync();
        List<Customer> customerList = await documents.ToListAsync();

        return await documents.ToListAsync();

    }

这是对集合字段建模的客户模型 POCO class:

    public class Customer
    {
        /// <summary>
        /// This attribute is used to map the Id property to the ObjectId in the collection
        /// </summary>
        [BsonId]
        public ObjectId Id { get; set; }

        [BsonElement("firstName")]
        public string firstName { get; set; }

        [BsonElement("lastName")]
        public string lastName { get; set; }

        [BsonElement("email")]
        public string Email { get; set; }

    }

CreateConnection 应该 return 它正在创建的集合 以便创建连接的人可以实际使用它:

//Consider renaming this method; you're really here to get the customers,
//not create a connection
public static YourCollectionType<BsonDocument> CreateConnection()
{
    var client = new MongoClient(connectionString);
    var database = client.GetDatabase("orders");
    //Get a handle on the customers collection:
    return database.GetCollection<BsonDocument>("customers");
}

FindCustomers 然后可以接受集合作为参数:

public async static Task<List<Customer>> FindCustomers(
    YourCollectionType<BsonDocument> collection)
{
    var documents =  await collection.Find(new BsonDocument()).ToListAsync();
    List<Customer> customerList = await documents.ToListAsync();

    return await documents.ToListAsync();
}

然后您可以使用 CreateConnection 创建要搜索的文档:

var customers = FindCustomers(CreateConnection());

如果 FindCustomers 仅在与 CreateConnection 创建的集合一起使用时才有意义,并且您永远不会将创建的对象用于任何其他用途,那么您可以 FindCustomer 直接调用 CreateConnection,但很可能这些条件不适用。