检查c#类值null, whitespace, empty, length,否则返回'unknown'

本文关键字:返回 unknown length 类值 null whitespace empty 检查 | 更新日期: 2023-09-27 18:18:43

我知道在c#中有100种做事方式。然而,我想知道我是否可以得到一些帮助,知道什么是测试值的好方法。在我的例子中,我有一个名为"目录"的属性在我的类,我想设置属性值为"未知",如果以下任何一个是真的

  • 是null
  • 是空
  • 是空白
  • 的长度== 0

伪代码…

String.IsNullOrEmpty(s);
s.Length == 0;
String.IsNullOrWhiteSpace(s);

我已经在我的代码中注释了我想做的事情。你们可能有更好的解决办法。

我班上

using System.Collections.ObjectModel;
using System.IO;
namespace Varo.Model
{
    public class DirectoryNode
    {
        public DirectoryNode(string filepath, INode parent)
        {
            // if filepath is empty || null || whitespace or || length.0
            // then set to 'Unknown' prior to creating the Directory info.
            this.File = new DirectoryInfo(filepath);
        }
        public DirectoryInfo File { get; private set; }
        public string Name
        {
            get { return this.File == null ? string.Empty : this.File.Name; }
        }
        public string Path
        {
            get { return this.File == null ? string.Empty : this.File.FullName; }
        }
    }
}

检查c#类值null, whitespace, empty, length,否则返回'unknown'

String.IsNullOrWhiteSpace一次做这些。

public string Directory
{
    get { 
        return String.IsNullOrWhiteSpace(this.SomeString) ? "unknown" : this.SomeString; 
    }
}