c# Generic classes and generic methods use examples

Generic class:

using System;

namespace ThreadDemo
{
    class Program
    {

        static void Main(string[] args)
        {
            MyStack<int> myStack = new MyStack<int>(3);
            myStack.Push(1);
            myStack.Push(2);
            myStack.Push(3);
            myStack.Push(4);

            MyStack<string> myStack1 = new MyStack<string>(5);
            myStack1.Push("张三");
        }
    }

    public class MyStack<T>
    {
        private T[] _stack;//栈数组
        private int _stackPoint;//当前位置
        private int _size;//栈的容量

        /// <summary>
        /// 初始化
        /// </summary>
        public MyStack(int size)
        {
            _size = size;
            _stack = new T[size];
            _stackPoint = 0;
        }

        /// <summary>
        /// 入栈方法
        /// </summary>
        /// <param name="item"></param>
        public void Push(T item)
        {
            if (_stackPoint >= _size)
            {
                Console.WriteLine("栈已满,无法继续入栈");
            }
            else
            {
                _stack[_stackPoint] = item;
                _stackPoint++;
            }

            foreach (var s in _stack)
            {
                Console.WriteLine(s);
            }
            Console.WriteLine("---------------------------");
        }

    }

}

Results of the:

The above example simulates the operation of data pushing into the stack. Using generics allows different types of data to be handled in a common class. Realize code reuse.

 

 Generic method:

using System;

namespace ThreadDemo
{
    class Program
    {
        /// <summary>
        /// 两个参数交换值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="left"></param>
        /// <param name="right"></param>
        static void Swip<T>(ref T left, ref T right)
        {
            T temp;
            temp = left;
            left = right;
            right = temp;
        }

        static void Main(string[] args)
        {
            int a = 1;
            int b = 2;
            Swip<int>(ref a, ref b);

            string s1 = "张三";
            string s2 = "李四";
            Swip<string>(ref s1, ref s2);

            Console.WriteLine("a={0},b={1}", a, b);
            Console.WriteLine("s1={0},s2={1}", s1, s2);

        }
    }



}

Results of the:

It can be seen that the values ​​of a, b, s1, and s2 are all exchanged.

The generic method here plays a role in the exchange of values ​​for different types of data, without the need to separately define methods for each type.

The ref keyword is used here, you can refer to https://blog.csdn.net/m0_37679113/article/details/83045813

 

 

Guess you like

Origin blog.csdn.net/liangmengbk/article/details/108952062