이러한 예제는 Func
및 Action
제네릭 대리자에서 공변성 및 반공변성을 사용하여 메서드를 재사용하고 코드에서 더 많은 유연성을 제공하는 방법을 보여 줍니다.
공변 및 반공변에 대한 자세한 내용은 대리자(C#)의 변형을 참조하세요.
공변 형식 매개 변수와 대리자 사용
다음 예제에서는 제네릭 Func
대리자에서 공변성 지원의 이점을 보여 줍니다. 메서드는 FindByTitle
형식의 매개 변수를 받아 String
형식의 객체를 반환합니다. 그러나 Func<String, Person>
가 Employee
을(를) 상속하므로 이 메서드를 Person
대리자에게 할당할 수 있습니다.
// Simple hierarchy of classes.
public class Person { }
public class Employee : Person { }
class Program
{
static Employee FindByTitle(String title)
{
// This is a stub for a method that returns
// an employee that has the specified title.
return new Employee();
}
static void Test()
{
// Create an instance of the delegate without using variance.
Func<String, Employee> findEmployee = FindByTitle;
// The delegate expects a method to return Person,
// but you can assign it a method that returns Employee.
Func<String, Person> findPerson = FindByTitle;
// You can also assign a delegate
// that returns a more derived type
// to a delegate that returns a less derived type.
findPerson = findEmployee;
}
}
반공변 형식 매개 변수와 대리자 사용
다음 예제에서는 제네릭 Action
대리자에서 반변성 지원의 이점을 보여 줍니다. 메서드는 AddToContacts
유형의 매개 변수를 Person
받습니다. 그러나 Action<Employee>
가 Employee
을(를) 상속하므로 이 메서드를 Person
대리자에게 할당할 수 있습니다.
public class Person { }
public class Employee : Person { }
class Program
{
static void AddToContacts(Person person)
{
// This method adds a Person object
// to a contact list.
}
static void Test()
{
// Create an instance of the delegate without using variance.
Action<Person> addPersonToContacts = AddToContacts;
// The Action delegate expects
// a method that has an Employee parameter,
// but you can assign it a method that has a Person parameter
// because Employee derives from Person.
Action<Employee> addEmployeeToContacts = AddToContacts;
// You can also assign a delegate
// that accepts a less derived parameter to a delegate
// that accepts a more derived parameter.
addEmployeeToContacts = addPersonToContacts;
}
}
참고하십시오
GitHub에서 Microsoft와 공동 작업
이 콘텐츠의 원본은 GitHub에서 찾을 수 있으며, 여기서 문제와 끌어오기 요청을 만들고 검토할 수도 있습니다. 자세한 내용은 참여자 가이드를 참조하세요.
.NET