Implementation of generics on Class in C#

黄舟
Release: 2016-12-27 14:09:11
Original
1302 people have browsed it

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>
Copy after login

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)!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template