[C#] 泛型(Generic)

  • 2354
  • 0
  • C#
  • 2015-05-17

摘要:[C#]泛型(Generics)

簡介:

泛型是將類別和方法將重複使用性、型別安全和高效率三者結合在一起,發揮了非泛型的類別和方法所無法提供的功能。

簡單說就是我不管傳入傳出型態,只管函式內的演算法處理就好,同樣的程式邏輯來處理不同型態的資料。

Sample1 應用於方法(Method):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GenericSapmle
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(GetProperty(123));
            Console.WriteLine(GetProperty("123"));
            Console.WriteLine(GetProperty(123.3));
            Console.ReadKey();
        }

        //Method
        static T GetProperty(T Property)
        {
            // do something
            return Property;
        }
    }
}

Sample2 應用於類別(Class):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GenericSapmle
{
    class Program
    {
        static void Main(string[] args)
        {
            Employee emp = new Employee("Eric", 95.5);
            Console.WriteLine("Eric"+emp.GetData());
            Employee emp1 = new Employee("John", 100);
            Console.WriteLine("John" + emp.GetData());
            Employee emp2 = new Employee("Jay", "120");
            Console.WriteLine("Jay" + emp.GetData());
            Console.ReadKey();
        }

        //Class
        public class Employee
        {
            private string _Name;
            private T _Salary;

            public Employee(string Name, T Salary)
            {
                _Name = Name;
                _Salary = Salary;
            }

            public T GetData()
            {
                return _Salary;
            }
        }
    }

}