Out generic modifier
Peponi │ 11/28/2024 │ 2m
C#
SyntaxKeywordModifier
Out generic modifier
11/28/2024
2m
Peponi
C#
SyntaxKeywordModifier
1. Introduction
out
키워드는 참조 형식 매개 변수를 공변
으로 할 수 있는 제네릭 한정자로 제네릭 인터페이스 선언 및 대리자에 사용할 수 있다.
- 대표적인 예시로는 IEnumerable<T> 인터페이스가 있다.
- 대리자의 경우 반환 형식으로만 사용 가능하다.
공변성
을 부여하여 암시적 변환에 의해 파생 형식의 사용이 가능해진다.
2. Example
public interface InterfaceA<out T>
{
Type GetType() => typeof(T);
}
public class ClassA<T> : InterfaceA<T>
{ }
private static void Main(string[] args)
{
InterfaceA<object> a = new ClassA<object>();
InterfaceA<List<int>> b = new ClassA<List<int>>();
a = b;
Console.WriteLine(a.GetType()); // ClassA`1[System.Collections.Generic.List`1[System.Int32]]
}
public delegate T DelegateA<out T>();
public static object GetObject() => new object();
public static List<int> GetInts() => new List<int>();
private static void Main(string[] args)
{
DelegateA<object> A = GetObject;
DelegateA<List<int>> B = GetInts;
A = B;
Console.WriteLine(A()); // System.Collections.Generic.List`1[System.Int32]
}