내용 보기
작성자
관리자 (IP : 106.247.248.10)
날짜
2025-07-22 08:35
제목
[C#] [스크랩] C# - 배열 및 Span의 공변성
| 예전에 아래의 글을 쓰면서, C# 언어의 공변성과 반공변성 ; https://www.sysnet.pe.kr/2/0/11513 
 public class Person { /* ...[생략]... */ }
public class Employee : Person 
{ 
    // ...[생략]...
    public override string ToString()
    {
        return $"{base.ToString()}, Position: {Position}";
    }
}
 internal class Program
{
    static void Main(string[] args)
    {
        Employee[] employees = {
            new Employee("Alice", 30, "Developer"),
            new Employee("Bob", 40, "Manager"),
            new Employee("Charlie", 35, "Designer")
        };
        Person[] people = employees; // C# 언어가 배열에 대해 공변을 허용하기 때문에 가능
        foreach (var person in people)
        {
            Console.WriteLine(person);
        }   
    }
}
 static void PrintPeople(Person[] people)
{
    foreach (var p in people)
    {
        Console.WriteLine(p);
    }
}
 static void PrintPeople(Person[] people) { // 런타임 시에 예외 발생 // Unhandled exception. System.ArrayTypeMismatchException: Attempted to access an element as a type incompatible with the array. people[0] = new Person("Dave", 28); // ...[생략]... } 
 
 C# 7.2 - Span<T> ; https://www.sysnet.pe.kr/2/0/11534 
 internal class Program
{
    static void Main(string[] args)
    {
        Employee[] employees = { /* ...[생략]... */ };
        // (이 코드는 C# 13까지만 컴파일이 됩니다. C# 14부터 컴피일 에러 - error CS1503)
        PrintPeople(employees); 
    }
    static void PrintPeople(Span<Person> people)
    {
        // 런타임 시 예외 발생 
        // Unhandled exception. System.ArrayTypeMismatchException: Attempted to access an element as a type incompatible with the array.
        people[0] = new Person("Dave", 28);
        foreach (var p in people)
        {
            Console.WriteLine(p);
        }
    }
}
 static void PrintPeople(ReadOnlySpan<Person> people)
{
    // Read-only이므로 대입을 시도하면 컴파일 오류 발생
    // people[0] = new Person("Dave", 28);
    foreach (var p in people)
    {
        Console.WriteLine(p);
    }
}
 | 
출처1
https://www.sysnet.pe.kr/2/0/13973
출처2