Home  >  Article  >  Backend Development  >  Implementation of generics on Class in C#

Implementation of generics on Class in C#

黄舟
黄舟Original
2016-12-27 14:09:111302browse

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            GenericArray<int> intArray = new GenericArray<int>(5);//实例化一个泛型的数组
            for (int i = 0; i < 5; i++)
            {
                intArray.SetItem(i, i * 5);
                Console.WriteLine(intArray.GetItem(i));
            }
            Console.WriteLine();
 
            //同样的方法用于字符串数组:
            GenericArray<char> charArray = new GenericArray<char>(5);
            for (int i = 0; i < 5; i++)
            {
                charArray.SetItem(i, (char)(i +97));
                Console.WriteLine(charArray.GetItem(i));
            }
        }
        public class GenericArray<t>
        {
            private T[] array;
            //构造函数
            public GenericArray(int size)
            {
                array = new T[size];
            }
            //读取方法
            public T GetItem(int index)
            {
                return array[index];
            }
            //赋值方法
            public void SetItem(int index, T value)
            {
                array[index] = value;
            }
        }
    }
}
</t></char></char></int></int>

The above is the content of the implementation of generics on Class in C#. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn