下麵這個字元串數組: 實現這個要求的方法也許會很多。下麵Insus.NET使用一個通用的方法來實現:面向對象,創建一個類別Class Digit: class Digit { private int _D; public int D { get { return _D; } set { _D = v ...
下麵這個字元串數組:
string[] str = { "3","y","34","QQ","41","adsf4","7","52"};
實現這個要求的方法也許會很多。下麵Insus.NET使用一個通用的方法來實現:
面向對象,創建一個類別Class Digit:
class Digit { private int _D; public int D { get { return _D; } set { _D = value; } } public Digit(int digit) { this._D = digit; } }Source Code
在類別中,添加2個方法,一是判斷元素是否為數字,另一個是是重寫ToString()方法:
public static bool TryParse(string str, out Digit digit) { digit = null; if (string.IsNullOrEmpty(str)) return false; int i; if (!int.TryParse(str, out i)) return false; digit = new Digit(i); return true; } public override string ToString() { return _D.ToString(); }Source Code
string[] str = { "3","y","34","QQ","41","adsf4","7","52"}; var result = new List<Digit>(); foreach (string s in str) { Digit d; if (Digit.TryParse(s, out d)) result.Add(d); } foreach (Digit d in result) { Console.WriteLine(d.ToString()); }Source Code