‘string’不包含’isNullorWhiteSpace’的定义

我不确定如何使用isNullorWhiteSpace将自己的方法合并到代码中,我的框架不是4.0。 我以前有一些帮助,他们建议使用isnullorwhitespace ,它不是最喜欢的显示方法:

2014年2月20日上午7:33:10,测量速度:0.2225

我似乎无法找到可行的等效代码。

  using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Collections; namespace conApp { class Program { public static class StringExtensions { public static bool IsNullOrWhiteSpace(string value) { if (value != null) { for (int i = 0; i < value.Length; i++) { if (!char.IsWhiteSpace(value[i])) { return false; } } } return true; } } static void Main(string[] args) { String line; try { using (StreamWriter sw = new StreamWriter("C:\\writetest\\writetest.txt")) { string mydirpath = "C:\\chat\\"; string[] txtFileList = Directory.GetFiles(mydirpath, "*.txt"); foreach (string txtName in txtFileList) { System.IO.StreamReader sr = new System.IO.StreamReader(txtName); while ((line = sr.ReadLine()) != null) { String spart = ".prt"; String sam = " AM"; String spm = " PM"; String sresult = "TEST RESULT: "; String svelocity = "MEASURED VELOCITY: "; String part = string.Empty; String date = string.Empty; String result = string.Empty; String velocity = string.Empty; // sw.WriteLine(line); if (line.Contains(sam) || line.Contains(spm)) { date = line; } if (line.Contains(spart)) { part = line; } if (line.Contains(sresult)) { result = line; } if (line.Contains(svelocity)) { velocity = line; } if (!String.IsNullOrWhiteSpace(date) && !String.IsNullOrWhiteSpace(velocity)) { bool isNullOrWhiteSpace = "foo bar".IsNullOrWhiteSpace(); //doesnt work here int I = 2; string[] x = new string[I]; x[0] = date; x[1] = velocity; sw.WriteLine(x[0] + "," + x[1]); } } } } } catch { } } } } 

首先, StringExtensions需要是顶级类,因此它不能在另一个类中。
其次,您需要通过将this关键字添加到第一个参数来将方法转换为扩展方法:

 public static bool IsNullOrWhiteSpace(this string value) 

所以它变成了:

 public static class StringExtensions { public static bool IsNullOrWhiteSpace(this string value) { if (value != null) { for (int i = 0; i < value.Length; i++) { if (!char.IsWhiteSpace(value[i])) { return false; } } } return true; } } class Program { ... }