page contents

C#中的泛型是什么?

王昭君 发布于 2022-11-28 16:01
阅读 725
收藏 0
分类:C/C++开发
4412
Nen
Nen
- 程序员

C# 中的泛型:


  • 提高性能。
  • 增加类型安全。
  • 减少重复代码。
  • 制作可重用的代码。


使用泛型,我们可以创建集合类。最好使用
System.Collections.Generic 命名空间而不是 System.Collections 命名空间中的类(例如 ArrayList)来创建泛型集合。泛型鼓励使用参数化类型,如下例所示:


using System;
namespace demoapp
{
    //We use < > to specify Parameter type 
    public class GFG<T>
    {
        //private data members 
        private T data;

        //using properties 
        public T value
        {
            /using accessors 
            get
            {
                return this.data;
            }
            set
            {
                this.data = value;
            }
        }
    }

    //vehicle class 
    class Vehicle
    {
        //Main method 
        static void Main(string[] args)
        {
            //instance of string type 
            GFG<string> company = new GFG<string>();
            company.value = "Tata motors";

            //instance of float type 
            GFG<float> version = new GFG<float>();
            version.value = 6.0F;

            //display Tata motors 
            Console.WriteLine(company.value);

            //display 6 
            Console.WriteLine(version.value);
        }
    }
}
请先 登录 后评论