从字符串数组中寻找数字的元素

前几天Insus.NET有写过一篇《从字符串数组中把数字的元素找出来http://www.cnblogs.com/insus/p/8001026.html 

和它的延伸篇《C# yield关键词使用http://www.cnblogs.com/insus/p/8003809.html

那是写一个类别来处理数字元素并收集起来。

开发程序,解决方法不是唯一的。相同的功能实现,方法不止一个。下面Insus.NET再使用另外的方法来实现,算作对基础知识的巩固与掌握。

参考下面代码:

 

上面#21至#30行代码,可以改用yield方法,返回循环结果:

 

 class Ak
    {
        private string[] _stringArray;

        public Ak(string[] stringArray)
        {
            this._stringArray = stringArray;
        }

        public IEnumerable<Digit> Result()
        {
            //  var result = new List<Digit>();
            foreach (string s in _stringArray)
            {
                string pattern = "^[0-9]";
                Regex regex = new Regex(pattern);
                if (regex.IsMatch(s))
                  yield return new Digit(Convert.ToInt32(s));
            }
            // return result;
        }
        public void Output()
        {
            foreach (Digit d in Result())
            {
                Console.WriteLine(d.ToString());
            }
        }
    }
Source Code

 

运行结果:

 

得到的结果与前一篇写自定义的方法进行验证的结果一样。

为了日后方便与维护,你可以把正则验计的代码,写成一个方法,或者是扩展方法,在程序需要正则验证时,直接使用这个方法即可。达到面向对象的三个要素这一,封装:

使用正则来处理,创建一个扩展方法:

 

public static bool Match(this string value, string pattern)
        {
            Regex regex = new Regex(pattern);
            return regex.IsMatch(value);
        }
Source Code


然后,程序代码最终可以变成这样子:

 

posted @ 2017-12-08 13:45  Insus.NET  阅读(421)  评论(0编辑  收藏  举报