C#检查动态值是否为null

时间:2011-11-22 22:07:34

标签: c# exception dynamic

我有一个具有动态参数的方法并返回动态结果。我希望能够将null,int,string等传递给我的方法。但是我在所有情况下都得到“NotSupportedException”。

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
}

1 个答案:

答案 0 :(得分: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.