Použití rozptylu pro obecné delegáty Func a Action (C#)

Tyto příklady ukazují, jak používat kovarianci a kontravariance v Func delegátech a Action obecné delegáty, abyste umožnili opakované použití metod a zajistili větší flexibilitu v kódu.

Další informace o kovarianci a kontravarianci naleznete v tématu Rozptyl v delegátech (C#).

Použití delegátů s parametry kovariantního typu

Následující příklad ukazuje výhody podpory kovariance v obecných Func delegátech. Metoda FindByTitle přebírá parametr String typu a vrací objekt typu Employee . Tuto metodu však můžete přiřadit delegátu Func<String, Person> , protože Employee dědí 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;  
  
    }  
}  

Použití delegátů s parametry kontravariantního typu

Následující příklad ukazuje výhody kontravariance podpory v obecných Action delegátech. Metoda AddToContacts přebírá parametr typu Person . Tuto metodu však můžete přiřadit delegátu Action<Employee> , protože Employee dědí 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;  
    }  
}  

Viz také