在C#中测试空值

jqw*_*wha 12 c# dataset

如果我这样做:

DataSet ds = GetMyDataset();

try
{
    string somevalue = ds.Tables[0].Rows[0]["col1"];
}
catch
{
    //maybe something was null
}
Run Code Online (Sandbox Code Playgroud)

有没有使用try/catch检查空值的好方法?只是我不关心"col1"中的值是否为空,或者如果"col1"不存在,或者如果没有返回行,或者如果表不存在!

也许我应该关心?:)也许try/catch是接近这个的最佳方式,但我只是想知道是否有另一种方法可以做到这一点?

谢谢!

Hen*_*man 7

不关心桌子或柱子有点奇怪.

例如,这是一种更为正常的做法table[0].Rows.Count == 0.

检查NULL值的最佳方法是使用if(...) ... else ....
最糟糕的方式是等待例外(以任何方式).


Sae*_*iri 0

我认为对于这种情况,Monad 可能是最好的选择(示例来自源代码):

public static TResult With<TInput, TResult>(this TInput o, 
       Func<TInput, TResult> evaluator)
       where TResult : class where TInput : class
{
  if (o == null) return null;
  return evaluator(o);
}

string postCode = this.With(x => person)
                      .With(x => x.Address)
                      .With(x => x.PostCode)
Run Code Online (Sandbox Code Playgroud)

对于你的情况类似于:

ds.With(x=>Tables[0]).With(x=>x.Rows).With(x=>x[0])...
Run Code Online (Sandbox Code Playgroud)

您将创建一个扩展类并使用它,而不必担心空引用,另外Return方法对您很有用,请参阅链接。