null / DBNull转换

时间:2013-05-14 18:08:09

标签: c# null dbnull

我有一个方法

void addParam(string name, object value);

和一个对象

public class Foo 
{
   public string Whatever;
}

执行符合此逻辑的(工作)调用的最佳方法是什么?

addParam("foo", Foo.Whatever == null ? DBNull.Value : Foo.Whatever);

我在考虑这样的事情:

object getParamValue(object value)
{
  if (value == null) return DBNull.Value;
  return value;
}

addParam("foo", getParamValue(ValueFoo.Whatever));

我如何实现这种行为?

1 个答案:

答案 0 :(得分:0)

您可以使用null coalesce operation:

addParam("foo", Foo.Whatever ?? DBNull.Value);