covariant 介面可讓其方法傳回的衍生類型比介面中指定的類型還要多。 Contravariant 介面可讓其方法接受的衍生型別參數,比介面中指定的參數還要少。
在 .NET Framework 4 中,數個現有的介面會變成共變數和反變數。 這些包括 IEnumerable<T> 和 IComparable<T>。 這可讓您將用於基底型別的泛型集合的方法重複用於衍生型別的集合。
如需 .NET 中的變體介面清單,請參閱 泛型介面中的變數 (C#) 。
轉換泛型集合
下列範例說明 介面中 IEnumerable<T> 共變數支援的優點。 方法 PrintFullName
接受型別的 IEnumerable<Person>
集合做為參數。 不過,您可以針對型別的 IEnumerable<Employee>
集合重複使用它,因為 Employee
會繼承 Person
。
// 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);
}
}
比較泛型集合
下列範例說明介面中 IEqualityComparer<T> 反變數支援的優點。
PersonComparer
類別會實作 IEqualityComparer<Person>
介面。 不過,您可以重複使用這個類別來比較型別的物件 Employee
序列,因為 Employee
會繼承 Person
。
// 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);
}
}