제네릭 컬렉션용 인터페이스의 가변성 사용(C# 및 Visual Basic)

공변(covariant) 인터페이스의 메서드는 인터페이스에 지정된 것보다 더 많은 파생 형식을 반환할 수 있고 반공변(contravariant) 인터페이스의 메서드는 인터페이스에 지정된 것보다 더 적은 파생 형식의 매개 변수를 받아들일 수 있습니다.

.NET Framework 4에서는 기존의 여러 인터페이스가 공변(covariant) 및 반공변(contravariant) 인터페이스로 사용됩니다. 여기에는 IEnumerable<T>IComparable<T>이 포함됩니다. 따라서 파생 형식의 컬렉션에 기본 형식의 제네릭 컬렉션과 함께 작동하는 메서드를 다시 사용할 수 있습니다.

.NET Framework의 variant 인터페이스 목록은 제네릭 인터페이스의 가변성(C# 및 Visual Basic)을 참조하십시오.

제네릭 컬렉션 변환

다음 예제에서는 IEnumerable<T> 인터페이스에서 지원하는 공변성(Covariance)의 이점을 보여 줍니다. PrintFullName 메서드는 IEnumerable<Person> 형식(Visual Basic의 경우 IEnumerable(Of Person))의 컬렉션을 매개 변수로 받아들입니다. 그러나 Employee가 Person을 상속하기 때문에 이 메서드를 IEnumerable<Employee> 형식(Visual Basic의 경우 IEnumerable(Of Person))에 다시 사용할 수 있습니다.

' Simple hierarchy of classes.
Public Class Person
    Public Property FirstName As String
    Public Property LastName As String
End Class

Public Class Employee
    Inherits Person
End Class

' The method has a parameter of the IEnumerable(Of Person) type.
Public Sub PrintFullName(ByVal persons As IEnumerable(Of Person))
    For Each person As Person In persons
        Console.WriteLine(
            "Name: " & person.FirstName & " " & person.LastName)
    Next
End Sub

Sub Main()
    Dim employees As IEnumerable(Of Employee) = New List(Of Employee)

    ' You can pass IEnumerable(Of Employee), 
    ' although the method expects IEnumerable(Of Person).

    PrintFullName(employees)

End Sub
// Simple hierarchy of classes.
public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public class Employee : Person { }

class Program
{
    // The method has a parameter of the IEnumerable<Person> type.
    public static void PrintFullName(IEnumerable<Person> persons)
    {
        foreach (Person person in persons)
        {
            Console.WriteLine("Name: {0} {1}",
            person.FirstName, person.LastName);
        }
    }

    public static void Test()
    {
        IEnumerable<Employee> employees = new List<Employee>();

        // You can pass IEnumerable<Employee>, 
        // although the method expects IEnumerable<Person>.

        PrintFullName(employees);

    }
}

제네릭 컬렉션 비교

다음 예제에서는 IComparer<T> 인터페이스에서 지원하는 반공변성(Contravariance)의 이점을 보여 줍니다. PersonComparer 클래스는 IComparer<Person> 인터페이스(Visual Basic의 경우 IComparer(Of Person))를 구현합니다. 그러나 Employee가 Person을 상속하기 때문에 이 클래스를 다시 사용하여 Employee 형식 개체의 시퀀스를 비교할 수 있습니다.

' Simple hierarhcy of classes.
Public Class Person
    Public Property FirstName As String
    Public Property LastName As String
End Class

Public Class Employee
    Inherits Person
End Class
' The custom comparer for the Person type
' with standard implementations of Equals()
' and GetHashCode() methods.
Class PersonComparer
    Implements IEqualityComparer(Of Person)

    Public Function Equals1(
        ByVal x As Person,
        ByVal y As Person) As Boolean _
        Implements IEqualityComparer(Of Person).Equals

        If x Is y Then Return True
        If x Is Nothing OrElse y Is Nothing Then Return False
        Return (x.FirstName = y.FirstName) AndAlso
            (x.LastName = y.LastName)
    End Function
    Public Function GetHashCode1(
        ByVal person As Person) As Integer _
        Implements IEqualityComparer(Of Person).GetHashCode

        If person Is Nothing Then Return 0
        Dim hashFirstName =
            If(person.FirstName Is Nothing,
            0, person.FirstName.GetHashCode())
        Dim hashLastName = person.LastName.GetHashCode()
        Return hashFirstName Xor hashLastName
    End Function
End Class

Sub Main()
    Dim employees = New List(Of Employee) From {
        New Employee With {.FirstName = "Michael", .LastName = "Alexander"},
        New Employee With {.FirstName = "Jeff", .LastName = "Price"}
    }

    ' You can pass PersonComparer, 
    ' which implements IEqualityComparer(Of Person),
    ' although the method expects IEqualityComparer(Of Employee)

    Dim noduplicates As IEnumerable(Of Employee) = employees.Distinct(New PersonComparer())

    For Each employee In noduplicates
        Console.WriteLine(employee.FirstName & " " & employee.LastName)
    Next
End Sub
// Simple hierarchy of classes.
public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public class Employee : Person { }

// The custom comparer for the Person type
// with standard implementations of Equals()
// and GetHashCode() methods.
class PersonComparer : IEqualityComparer<Person>
{
    public bool Equals(Person x, Person y)
    {            
        if (Object.ReferenceEquals(x, y)) return true;
        if (Object.ReferenceEquals(x, null) ||
            Object.ReferenceEquals(y, null))
            return false;            
        return x.FirstName == y.FirstName && x.LastName == y.LastName;
    }
    public int GetHashCode(Person person)
    {
        if (Object.ReferenceEquals(person, null)) return 0;
        int hashFirstName = person.FirstName == null
            ? 0 : person.FirstName.GetHashCode();
        int hashLastName = person.LastName.GetHashCode();
        return hashFirstName ^ hashLastName;
    }
}

class Program
{

    public static void Test()
    {
        List<Employee> employees = new List<Employee> {
               new Employee() {FirstName = "Michael", LastName = "Alexander"},
               new Employee() {FirstName = "Jeff", LastName = "Price"}
            };

        // You can pass PersonComparer, 
        // which implements IEqualityComparer<Person>,
        // although the method expects IEqualityComparer<Employee>.

        IEnumerable<Employee> noduplicates =
            employees.Distinct<Employee>(new PersonComparer());

        foreach (var employee in noduplicates)
            Console.WriteLine(employee.FirstName + " " + employee.LastName);
    }
}

참고 항목

개념

제네릭 인터페이스의 가변성(C# 및 Visual Basic)