Func ve Eylem Genel Temsilcileri için Varyansı Kullanma (C#)

Bu örnekler, yöntemlerin yeniden kullanılmasını sağlamak ve kodunuzda daha fazla esneklik sağlamak için ve Action genel temsilcilerde Func kovaryans ve ters değişken kullanmayı gösterir.

Kovaryans ve değişken karşıtı hakkında daha fazla bilgi için bkz . Temsilcilerde Varyans (C#).

Birlikte Değişken Türü Parametreleriyle Temsilcileri Kullanma

Aşağıdaki örnek, genel Func temsilcilerde kovaryans desteğinin avantajlarını göstermektedir. yöntemi türündeki FindByTitle bir parametreyi String alır ve türünde bir nesne Employee döndürür. Ancak, devraldığından Personbu yöntemi temsilciye Func<String, Person>Employee atayabilirsiniz.

// 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;  
  
    }  
}  

Delegeleri Değişken Karşıtı Tür Parametreleriyle Kullanma

Aşağıdaki örnek, genel Action temsilcilerde değişken karşıtı desteğin avantajlarını göstermektedir. AddToContacts yöntemi, türünde bir parametre Person alır. Ancak, devraldığından Personbu yöntemi temsilciye Action<Employee>Employee atayabilirsiniz.

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;  
    }  
}  

Ayrıca bkz.