下面这个字符串数组:
string[] str = { "3","y","34","QQ","41","adsf4","7","52"};
实现这个要求的方法也许会很多。下面Insus.NET使用一个通用的方法来实现:
面向对象,创建一个类别Class Digit:
class="code_img_closed" src="/Upload/Images/2017120723/0015B68B3C38AA5B.gif" alt="" />logs_code_hide('1090141c-ae41-4750-b582-4176fc5187cb',event)" src="/Upload/Images/2017120723/2B1B950FA3DF188F.gif" alt="" />
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