2011-11-22 63 views
-6

我有具有動態參數並返回一個動態結果的方法。我希望能夠將null,int,string等傳入我的方法。但是,在所有情況下,我都會得到「NotSupportedException」。C#檢查動態值對空

MyMethod(null); // Causes problems (Should resolve to ref type?) 
MyMethod(0); // Causes problems (Should resolve to int type) 

public dynamic MyMethod(dynamic b) 
{ 
    if (value != null) {...}// Throws NotSupportedExpception 
    if (value != 0) {...} // Throws NotSupportedExpception 
} 
+5

爲什麼要使用動態? – Joe

+5

什麼是「價值」,爲什麼「b」不被使用?這段代碼很混亂。 –

+5

你的方法似乎爲我工作的罰款(後我改名'B'到'value')。什麼是異常的調用堆棧? – svick

回答

5

它只是工作

static void Main(string[] args) 
    { 
     MyMethod(null); 
     MyMethod(0); 

    }   
    public static dynamic MyMethod(dynamic value) 
    { 
     if (value != null) 
      Console.WriteLine("Value is not null."); 
     if (value != 0) 
      Console.WriteLine("Value is not 0."); 

     return value; 
    } 

輸出

Value is not 0. 
Value is not null. 
+0

問題是最近在VS2010我能打破所有異常(在調試 - >例外)。正在觸發的異常是「公共語言運行時異常」下的「System.NotSupportedException」。如果我在此異常之後繼續或將其關閉,代碼將正確運行。是不是所有例外都不好,應該解決?正如我所描述的,其他人是否會開啓異常中斷? – aidesigner