检查C#类值null、空格、空、长度,否则返回';未知';

检查C#类值null、空格、空、长度,否则返回';未知';,c#,class,C#,Class,我知道在C#中有100种做事的方法。然而,我想知道我是否可以得到一些帮助,知道什么是测试一个值的好方法。在我的示例中,我的类中有一个名为“Directory”的属性,如果以下任何一项为真,我希望将属性值设置为“Unknown” 是空的 是空的 是空白 长度=0 伪代码… String.IsNullOrEmpty(s); s.Length == 0; String.IsNullOrWhiteSpace(s); 我已经在我的代码中注释了我要做的事情。你们可能有更好的解决办法 我的班级 us

我知道在C#中有100种做事的方法。然而,我想知道我是否可以得到一些帮助,知道什么是测试一个值的好方法。在我的示例中,我的类中有一个名为“Directory”的属性,如果以下任何一项为真,我希望将属性值设置为“Unknown”

  • 是空的
  • 是空的
  • 是空白
  • 长度=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; }
        }
    }
}
一次完成所有任务

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

没有一个正确的答案——每个答案都有不同的目的,因此存在不同的方法
IsNullOrWhiteSpace
封装了所有这些代码,因此,如果这是您想要检查的内容,请使用它。查看IsNullOrWhiteSpace代码-这是您需要的。