2016-08-24 63 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