ASP.NET C#
Generic(제너릭)
ToKor
2021. 1. 27. 02:24
공통된 코드를 사용하고, 타입만 달라질 경우 사용
1. 일반적인 클래스 사용 (int, string)
// int id, string name
using System;
namespace Example
{
public class Student
{
public int id {get; set;}
public string name {get; set;}
public Student(int id, string name)
{
this.id = id;
this.name = name;
}
public int getId()
{
return this.id;
}
public string getName()
{
return this.name;
}
}
public class Program
{
// execute
public static void Main(string[] args)
{
Student st = new Student(10, "John");
Console.WriteLine(st.getName() + "'s ID is " + st.getId());
}
}
}
2. 일반적인 코드 사용(string id, string name) 그런데 타입만 달라진다.
// string id, string name
using System;
namespace Example
{
public class Student
{
public string id {get; set;}
public string name {get; set;}
public Student(string id, string name)
{
this.id = id;
this.name = name;
}
public string getId()
{
return this.id;
}
public string getName()
{
return this.name;
}
}
public class Program
{
// execute
public static void Main(string[] args)
{
Student st = new Student("ten", "John");
Console.WriteLine(st.getName() + "'s ID is " + st.getId());
}
}
}
3. 코드의 낭비를 없애기 위해 제너릭 사용
: 클래스 선언시 이름 옆에 <T>, 타입이 들어가는 자리에 T로 표기
: 사용시에는 클래스 이름옆에 <타입>을 넣어준다
// 제네릭 T : 한개의 변수 사용예정, string id, string name
using System;
namespace Example
{
public class Student<T>
{
public T id {get; set;}
public T name {get; set;}
public Student(T id, T name)
{
this.id = id;
this.name = name;
}
public T getId()
{
return this.id;
}
public T getName()
{
return this.name;
}
}
public class Program
{
// execute
public static void Main(string[] args)
{
Student<string> st = new Student<string>("ten", "John");
Console.WriteLine(st.getName() + "'s ID is " + st.getId());
}
}
}
4. 제네릭 2개의 변수 사용
// 제네릭 T,S 사용
using System;
namespace Example
{
public class Student<T, S>
{
public T id {get; set;}
public S name {get; set;}
public Student(T id, S name)
{
this.id = id;
this.name = name;
}
public T getId()
{
return this.id;
}
public S getName()
{
return this.name;
}
}
public class Program
{
// execute
public static void Main(string[] args)
{
Student<int, string> st = new Student<int, string>(10, "John");
Console.WriteLine(st.getName() + "'s ID is " + st.getId());
}
}
}