2016-08-24 67 views
1

我想要实现的是基于我的方法获得的动态初始化“过滤器”变量。动态初始化var过滤器

  • 将其初始化为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

变量不是一个动态变量,它是一个关键字type inference。这些是非常不同的概念。关键问题是,在你的代码片段中,编译器无法弄清楚你希望你的变量是什么类型的变量。

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

谢谢!我虽然'var'类型就像javascript类型。它将var类型更改为动态后工作 – Gino

0

随着var它是一个隐式类型并且可以初始化一个隐式类型变量null因为它可以是既值类型和引用类型;并且值类型不能被分配给null(除非它被明确地置为null)。

因此,不是说var filter=null;,你应该明确地指定类型

BsonDocument filter = null; 
+0

未接受,因为如果我将过滤器设置为'BsonDocument',则在此引发错误'filter = builder.Eq(“Categories.Sub.id”,id);'因为它返回一个不同的类型。 – Gino