动态初始化var过滤器

时间:2016-08-24 18:29:42

标签: c# mongodb mongodb-query

我想要实现的是根据我的方法获取动态初始化“过滤器”变量。

  • 将其初始化为null会引发错误。
  • 留空投掷错误。
  • 将其设置为泛型类型会引发错误
  • 将其设置为新BsonDocument也会引发错误

这是我的代码:

var filter=null;

if (id != 0)
    if (subID != 0)
        //Get Specific Categories
        filter = builder.Eq("Categories.Sub.id", id) & builder.Eq("Categories.Sub.Custom.id", subID);
    else
        //Get SubCategories
        filter = builder.Eq("Categories.Sub.id", id);
else
    //Get Generic Categories
    filter = new BsonDocument();

我一直在寻找,但似乎没有人有我的问题,或者我找不到它。

2 个答案:

答案 0 :(得分:2)

Var不是动态变量,它是type inference的关键字。这些是非常不同的概念。关键问题是,在您的代码段中,编译器无法确定您希望var使用哪种变量。

var myNumber = 3; // myNumber is inferred by the compiler to be of type int.

int myNumber = 3; // this line is considered by the computer to be identical to the one above.

var变量的推断类型不会改变。

var myVariable = 3;
myVariable = "Hello"; // throws an error because myVariable is of type int

动态变量的类型可以更改。

dynamic myVariable = 3;
myVariable = "Hello"; // does not throw an error.

编译器必须能够在创建var变量时确定对象的类型;

var myVariable = null; // null can be anything, the compiler can not figure out what kind of variable you want.

var myVariable = (BsonDocument)null; // by setting the variable to a null instance of a specific type the compiler can figure out what to set var to.

答案 1 :(得分:0)

使用var它是一个隐式类型,您可以将隐式类型变量初始化为null,因为它可以是值类型和引用类型;和值类型不能赋值为null(除非另有明确的可以为空)。

因此,您应该明确指定类型

,而不是说var filter=null;
BsonDocument filter = null;