字符串阵列分别输出元素的索引,原值和长度

下面有一个字符串阵列:

string[] strArr = { "adg45","frwqer","sfd5rtgsd","pdlfd**l","qr$%Ulf5fjk","hlef"};


当你接到这个问题时,你是怎样解决写实现呢?直接写代码?还是运行面向对象的思维来开发呢?

既然有此一问,下面Insus.NET分享自己的实现方法:

创建一个对象,即代字符串阵列中每一个元素的对象:

 

 class Item
    {
        private int _Index;
        public int Index
        {
            get { return _Index; }
            set { _Index = value; }
        }

        private string _Code;
        public string Code
        {
            get { return _Code; }
            set { _Code = value; }
        }

        private int _Length;
        public int Length
        {
            get { return _Length; }
            set { _Length = value; }
        }

        public Item() { }

        public Item(int index, string code, int length)
        {
            this._Index = index;
            this._Code = code;
            this._Length = length;
        }

        public override string ToString()
        {
            return string.Format("Index: {0}, Code: {1}, Length: {2}", _Index, _Code, _Length);
        }
    }
Source Code

 

接下来,我们创建另外一个类,处理数据并把处理好的结果存储于一个集合中:


 class ItemUtility
    {
        public List<Item> Items = new List<Item>();

        public void Add(int index, string code)
        {
            AppendItem(index, code, code.Length);
        }

        private void AppendItem(int index, string code, int length)
        {
            var item = new Item { Index = index,Code = code,Length = length};
            Items.Add(item);
        }
    }
Source Code

 

上面的类别,均是在程序里进行封装,专供程序引用与呼叫。

写程序的用户就使用拿来使用:

 

 class Am
    {
        private string[] _StringArray;

        public Am(string[] stringArray)
        {
            this._StringArray = stringArray;
        }

        public void Process()
        {
            ItemUtility utility = new ItemUtility();
            int idx = 0;
            foreach (string s in _StringArray)
            {
                utility.Add(++idx, s);
            }

            var result = utility.Items;
            foreach (Item item in result)
            {
                Console.WriteLine(item.ToString());
            }
        }
    }
Source Code


那在控制台运行上面的程序Am()

 

在控制台代码中,只有输出与输出,没有必要在这里写过多的代码。
达到面向对象编程的思维,封装。

posted @ 2017-12-09 09:46  Insus.NET  阅读(451)  评论(0编辑  收藏  举报