In generic modifier
Peponi │ 11/28/2024 │ 2m
C#
SyntaxKeywordModifier
In generic modifier
11/28/2024
2m
Peponi
C#
SyntaxKeywordModifier
1. Introduction
in
키워드는 참조 형식 매개 변수를 반공변
으로 할 수 있는 제네릭 한정자로 제네릭 인터페이스 선언 및 대리자에 사용할 수 있다.
- IComparer<T> 같은 인터페이스가 이를 이용해 구현되어 있다.
- 대리자의 경우 반환 형식이
void
이며 파라미터에 형식이 정의되는 경우 사용 가능하다.
반공변성
을 부여하여 암시적 변환에 의해 상위 형식의 사용이 가능해진다.
2. Example
public interface InterfaceA<in T>
{
Type GetType() => typeof(T);
}
public class ClassA<T> : InterfaceA<T>
{ }
private static void Main(string[] args)
{
InterfaceA<List<int>> a = new ClassA<List<int>>();
InterfaceA<object> b = new ClassA<object>();
a = b;
Console.WriteLine(a.GetType()); // ClassA`1[System.Object]
}
public delegate void DelegateA<in T>(T param);
public static void PutInts(List<int> param) => Console.WriteLine("List");
public static void PutObject(object param) => Console.WriteLine("object");
private static void Main(string[] args)
{
DelegateA<List<int>> A = PutInts;
DelegateA<object> B = PutObject;
A = B;
A(new List<int>());
// output : object
}