Пример ковариации и контравариантности в реальном мире
У меня возникли проблемы с пониманием того, как я буду использовать ковариацию и контравариантность в реальном мире.
До сих пор единственными примерами, которые я видел, был тот же самый пример старого массива.
object[] objectArray = new string[] { "string 1", "string 2" };
Было бы неплохо увидеть пример, который позволил бы мне использовать его во время моей разработки, если бы я мог видеть, что он используется в другом месте.
Ответы
Ответ 1
Допустим, у вас есть класс Person и класс, производный от него, Учитель. У вас есть некоторые операции, которые принимают IEnumerable<Person>
в качестве аргумента. В вашем школьном классе у вас есть метод, который возвращает IEnumerable<Teacher>
. Ковариантность позволяет вам напрямую использовать этот результат для методов, которые принимают IEnumerable<Person>
, заменяя более производный тип менее производным (более универсальным) типом. Контравариантность, напротив, позволяет вам использовать более общий тип, где указывается более производный тип.
См. Также Ковариантность и Контравариантность в обобщениях на MSDN.
Классы:
public class Person
{
public string Name { get; set; }
}
public class Teacher : Person { }
public class MailingList
{
public void Add(IEnumerable<out Person> people) { ... }
}
public class School
{
public IEnumerable<Teacher> GetTeachers() { ... }
}
public class PersonNameComparer : IComparer<Person>
{
public int Compare(Person a, Person b)
{
if (a == null) return b == null ? 0 : -1;
return b == null ? 1 : Compare(a,b);
}
private int Compare(string a, string b)
{
if (a == null) return b == null ? 0 : -1;
return b == null ? 1 : a.CompareTo(b);
}
}
Использование:
var teachers = school.GetTeachers();
var mailingList = new MailingList();
// Add() is covariant, we can use a more derived type
mailingList.Add(teachers);
// the Set<T> constructor uses a contravariant interface, IComparer<T>,
// we can use a more generic type than required.
// See https://msdn.microsoft.com/en-us/library/8ehhxeaf.aspx for declaration syntax
var teacherSet = new SortedSet<Teachers>(teachers, new PersonNameComparer());
Ответ 2
// Contravariance
interface IGobbler<in T> {
void gobble(T t);
}
// Since a QuadrupedGobbler can gobble any four-footed
// creature, it is OK to treat it as a donkey gobbler.
IGobbler<Donkey> dg = new QuadrupedGobbler();
dg.gobble(MyDonkey());
// Covariance
interface ISpewer<out T> {
T spew();
}
// A MouseSpewer obviously spews rodents (all mice are
// rodents), so we can treat it as a rodent spewer.
ISpewer<Rodent> rs = new MouseSpewer();
Rodent r = rs.spew();
Для полноты...
// Invariance
interface IHat<T> {
void hide(T t);
T pull();
}
// A RabbitHat…
IHat<Rabbit> rHat = RabbitHat();
// …cannot be treated covariantly as a mammal hat…
IHat<Mammal> mHat = rHat; // Compiler error
// …because…
mHat.hide(new Dolphin()); // Hide a dolphin in a rabbit hat??
// It also cannot be treated contravariantly as a cottontail hat…
IHat<CottonTail> cHat = rHat; // Compiler error
// …because…
rHat.hide(new MarshRabbit());
cHat.pull(); // Pull a marsh rabbit out of a cottontail hat??
Ответ 3
Вот что я собрал, чтобы помочь понять разницу
public interface ICovariant<out T> { }
public interface IContravariant<in T> { }
public class Covariant<T> : ICovariant<T> { }
public class Contravariant<T> : IContravariant<T> { }
public class Fruit { }
public class Apple : Fruit { }
public class TheInsAndOuts
{
public void Covariance()
{
ICovariant<Fruit> fruit = new Covariant<Fruit>();
ICovariant<Apple> apple = new Covariant<Apple>();
Covariant(fruit);
Covariant(apple); //apple is being upcasted to fruit, without the out keyword this will not compile
}
public void Contravariance()
{
IContravariant<Fruit> fruit = new Contravariant<Fruit>();
IContravariant<Apple> apple = new Contravariant<Apple>();
Contravariant(fruit); //fruit is being downcasted to apple, without the in keyword this will not compile
Contravariant(apple);
}
public void Covariant(ICovariant<Fruit> fruit) { }
public void Contravariant(IContravariant<Apple> apple) { }
}
TL;DR
ICovariant<Fruit> apple = new Covariant<Apple>(); //because it covariant
IContravariant<Apple> fruit = new Contravariant<Fruit>(); //because it contravariant
Ответ 4
Ключи in и out управляют правилами литья компилятора для интерфейсов и делегатов с общими параметрами:
interface IInvariant<T> {
// This interface can not be implicitly cast AT ALL
// Used for non-readonly collections
IList<T> GetList { get; }
// Used when T is used as both argument *and* return type
T Method(T argument);
}//interface
interface ICovariant<out T> {
// This interface can be implicitly cast to LESS DERIVED (upcasting)
// Used for readonly collections
IEnumerable<T> GetList { get; }
// Used when T is used as return type
T Method();
}//interface
interface IContravariant<in T> {
// This interface can be implicitly cast to MORE DERIVED (downcasting)
// Usually means T is used as argument
void Method(T argument);
}//interface
class Casting {
IInvariant<Animal> invariantAnimal;
ICovariant<Animal> covariantAnimal;
IContravariant<Animal> contravariantAnimal;
IInvariant<Fish> invariantFish;
ICovariant<Fish> covariantFish;
IContravariant<Fish> contravariantFish;
public void Go() {
// NOT ALLOWED invariants do *not* allow implicit casting:
invariantAnimal = invariantFish;
invariantFish = invariantAnimal; // NOT ALLOWED
// ALLOWED covariants *allow* implicit upcasting:
covariantAnimal = covariantFish;
// NOT ALLOWED covariants do *not* allow implicit downcasting:
covariantFish = covariantAnimal;
// NOT ALLOWED contravariants do *not* allow implicit upcasting:
contravariantAnimal = contravariantFish;
// ALLOWED contravariants *allow* implicit downcasting
contravariantFish = contravariantAnimal;
}//method
}//class
// .NET Framework Examples:
public interface IList<T> : ICollection<T>, IEnumerable<T>, IEnumerable { }
public interface IEnumerable<out T> : IEnumerable { }
class Delegates {
// When T is used as both "in" (argument) and "out" (return value)
delegate T Invariant<T>(T argument);
// When T is used as "out" (return value) only
delegate T Covariant<out T>();
// When T is used as "in" (argument) only
delegate void Contravariant<in T>(T argument);
// Confusing
delegate T CovariantBoth<out T>(T argument);
// Confusing
delegate T ContravariantBoth<in T>(T argument);
// From .NET Framework:
public delegate void Action<in T>(T obj);
public delegate TResult Func<in T, out TResult>(T arg);
}//class
Ответ 5
class A {}
class B : A {}
public void SomeFunction()
{
var someListOfB = new List<B>();
someListOfB.Add(new B());
someListOfB.Add(new B());
someListOfB.Add(new B());
SomeFunctionThatTakesA(someListOfB);
}
public void SomeFunctionThatTakesA(IEnumerable<A> input)
{
// Before C# 4, you couldn't pass in List<B>:
// cannot convert from
// 'System.Collections.Generic.List<ConsoleApplication1.B>' to
// 'System.Collections.Generic.IEnumerable<ConsoleApplication1.A>'
}
В принципе, всякий раз, когда у вас есть функция, которая принимает Enumerable одного типа, вы не можете передать в Enumerable производного типа без явно его литья.
Просто, чтобы предупредить вас о ловушке:
var ListOfB = new List<B>();
if(ListOfB is IEnumerable<A>)
{
// In C# 4, this branch will
// execute...
Console.Write("It is A");
}
else if (ListOfB is IEnumerable<B>)
{
// ...but in C# 3 and earlier,
// this one will execute instead.
Console.Write("It is B");
}
Это ужасный код в любом случае, но он существует, и изменение поведения на С# 4 может привести к тонким и сложным поискам ошибок, если вы используете такую конструкцию.
Ответ 6
Вот простой пример использования иерархии наследования.
Учитывая простую иерархию классов:
![enter image description here]()
И в коде:
public abstract class LifeForm { }
public abstract class Animal : LifeForm { }
public class Giraffe : Animal { }
public class Zebra : Animal { }
Инвариантность (т.е. параметры общего типа * не * украшены ключевыми словами in
или out
)
По-видимому, такой метод, как этот
public static void PrintLifeForms(IList<LifeForm> lifeForms)
{
foreach (var lifeForm in lifeForms)
{
Console.WriteLine(lifeForm.GetType().ToString());
}
}
... должен принять гетерогенную коллекцию: (что он делает)
var myAnimals = new List<LifeForm>
{
new Giraffe(),
new Zebra()
};
PrintLifeForms(myAnimals); // Giraffe, Zebra
Однако передать коллекцию более производного типа не удается!
var myGiraffes = new List<Giraffe>
{
new Giraffe(), // "Jerry"
new Giraffe() // "Melman"
};
PrintLifeForms(myGiraffes); // Compile Error!
cannot convert from 'System.Collections.Generic.List<Giraffe>' to 'System.Collections.Generic.IList<LifeForm>'
Зачем? Поскольку универсальный параметр IList<LifeForm>
не является ковариантным - IList<T>
является инвариантным, поэтому IList<LifeForm>
принимает только коллекции (которые реализуют IList), где параметризованный тип T
должен быть LifeForm
.
Если реализация метода PrintLifeForms
была вредоносной (но имеет PrintLifeForms
же сигнатуру метода), причина, по которой компилятор предотвращает передачу List<Giraffe>
становится очевидной:
public static void PrintLifeForms(IList<LifeForm> lifeForms)
{
lifeForms.Add(new Zebra());
}
Поскольку IList
допускает добавление или удаление элементов, любой подкласс LifeForm
может, таким образом, быть добавлен к параметру lifeForms
и нарушать тип любой коллекции производных типов, передаваемых методу. (Здесь злонамеренный метод попытается добавить Zebra
к var myGiraffes
). К счастью, компилятор защищает нас от этой опасности.
Ковариантность (универсальный с параметризованным типом, украшенным out
)
Ковариантность широко используется с неизменяемыми коллекциями (т.е. Когда новые элементы не могут быть добавлены или удалены из коллекции)
Решение приведенного выше примера состоит в том, чтобы обеспечить использование ковариантного универсального типа коллекции, например IEnumerable
(определяется как IEnumerable<out T>
). IEnumerable
не имеет методов для изменения в коллекцию, и в результате out
ковариации любая коллекция с подтипом LifeForm
теперь может быть передана методу:
public static void PrintLifeForms(IEnumerable<LifeForm> lifeForms)
{
foreach (var lifeForm in lifeForms)
{
Console.WriteLine(lifeForm.GetType().ToString());
}
}
PrintLifeForms
теперь можно вызывать с помощью Zebras
, Giraffes
и любого IEnumerable<>
любого подкласса LifeForm
Contravariance (универсальный с параметризованным типом, декорированным с помощью in
)
Контравариантность часто используется, когда функции передаются в качестве параметров.
Вот пример функции, которая принимает Action<Zebra>
в качестве параметра и вызывает его в известном экземпляре Zebra:
public void PerformZebraAction(Action<Zebra> zebraAction)
{
var zebra = new Zebra();
zebraAction(zebra);
}
Как и ожидалось, это работает просто отлично:
var myAction = new Action<Zebra>(z => Console.WriteLine("I'm a zebra"));
PerformZebraAction(myAction); // I'm a zebra
Интуитивно понятно, что это не удастся:
var myAction = new Action<Giraffe>(g => Console.WriteLine("I'm a giraffe"));
PerformZebraAction(myAction);
cannot convert from 'System.Action<Giraffe>' to 'System.Action<Zebra>'
Однако это удается
var myAction = new Action<Animal>(a => Console.WriteLine("I'm an animal"));
PerformZebraAction(myAction); // I'm an animal
и даже это тоже удается
var myAction = new Action<object>(a => Console.WriteLine("I'm an amoeba"));
PerformZebraAction(myAction); // I'm an amoeba
Зачем? Поскольку Action
определяется как Action<in T>
, то есть он является contravariant
, что означает, что для Action<Zebra> myAction
, что myAction
может быть не более чем Action<Zebra>
, но менее производные суперклассы Zebra
также приемлемы.
Хотя вначале это может быть не интуитивно понятно (например, как можно передать Action<object>
в качестве параметра, требующего Action<Zebra>
?), Если вы распакуете шаги, вы заметите, что вызываемая функция (PerformZebraAction
) сама отвечает за для передачи данных (в данном случае экземпляра Zebra
) в функцию - данные не поступают из вызывающего кода.
Из-за перевернутого подхода с использованием функций более высокого порядка, таким образом, к тому времени, Action
вызывается, это более производный Zebra
экземпляр, который вызывается против zebraAction
функции (передается в качестве параметра), хотя сама функция использует менее производный тип.
Ответ 7
Из MSDN
В следующем примере кода показана поддержка ковариации и контравариантности для групп методов
static object GetObject() { return null; }
static void SetObject(object obj) { }
static string GetString() { return ""; }
static void SetString(string str) { }
static void Test()
{
// Covariance. A delegate specifies a return type as object,
// but you can assign a method that returns a string.
Func<object> del = GetString;
// Contravariance. A delegate specifies a parameter type as string,
// but you can assign a method that takes an object.
Action<string> del2 = SetObject;
}
Ответ 8
Делегатор конвертера помогает мне визуализировать обе концепции совместной работы:
delegate TOutput Converter<in TInput, out TOutput>(TInput input);
TOutput
представляет ковариацию, где метод возвращает более конкретный тип.
TInput
представляет контравариантность, где метод передается менее конкретным типом.
public class Dog { public string Name { get; set; } }
public class Poodle : Dog { public void DoBackflip(){ System.Console.WriteLine("2nd smartest breed - woof!"); } }
public static Poodle ConvertDogToPoodle(Dog dog)
{
return new Poodle() { Name = dog.Name };
}
List<Dog> dogs = new List<Dog>() { new Dog { Name = "Truffles" }, new Dog { Name = "Fuzzball" } };
List<Poodle> poodles = dogs.ConvertAll(new Converter<Dog, Poodle>(ConvertDogToPoodle));
poodles[0].DoBackflip();