Megosztás a következőn keresztül:


Variancia használata Func és Action Generic meghatalmazottakhoz (C#)

Ezek a példák bemutatják, hogyan használhatja a kovarianciát és a kovarianciát az általános Action meghatalmazottakban a Func metódusok újrafelhasználásának engedélyezéséhez és a kód rugalmasságának biztosításához.

A kovarianciáról és a kovátváriságról további információt a Meghatalmazottak varianciája (C#) című témakörben talál.

Meghatalmazottak használata Covariant-típusparaméterekkel

Az alábbi példa a kovarianciatámogatás előnyeit mutatja be az általános Func meghatalmazottakban. A FindByTitle metódus a típus paraméterét String veszi fel, és visszaadja a Employee típus egy objektumát. Ezt a metódust azonban hozzárendelheti a Func<String, Person> meghatalmazotthoz, mert Employee örökli 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;  
  
    }  
}  

Meghatalmazottak használata Contravariant típusú paraméterekkel

Az alábbi példa a contravariance támogatás előnyeit mutatja be az általános Action meghatalmazottakban. A AddToContacts metódus egy ilyen típusú paramétert Person használ. Ezt a metódust azonban hozzárendelheti a Action<Employee> meghatalmazotthoz, mert Employee örökli 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;  
    }  
}  

Lásd még