协方差和逆变现实世界的例子 [英] Covariance and contravariance real world example

查看:125
本文介绍了协方差和逆变现实世界的例子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小麻烦理解我怎么会用协变和逆变在现实世界中。

I'm having a little trouble understanding how I would use covariance and contravariance in the real world.

到目前为止,我已经看到过相同的旧阵列例如唯一的例子。

So far, the only examples I've seen have been the same old array example.

object[] objectArray = new string[] { "string 1", "string 2" };

这将是很好看一个例子,让我到我的开发过程中使用它,如果我能看到它在别处使用。

It would be nice to see an example that would allow me to use it during my development if I could see it being used elsewhere.

推荐答案

让我们假设你有一个类Person和提炼出来的,老师一类。你有一些操作采取的IEnumerable<&人GT; 作为参数。在学校类,你有一个返回值 A方法IEnumerable<教师与GT; 。协方差,您可以直接使用该结果对于采取方法的IEnumerable<人> ,一个不太导出(更通用)取代更派生类型类型。逆变,与直觉相​​反,让你使用更通用的类型,其中指定了多个派生型。另请参见 https://msdn.microsoft.com/en-us/library/dd799517的.aspx

Let's say you have a class Person and a class that derives from it, Teacher. You have some operations that take an IEnumerable<Person> as the argument. In your School class you have a method that returns an IEnumerable<Teacher>. Covariance allows you to directly use that result for the methods that take an IEnumerable<Person>, substituting a more derived type for a less derived (more generic) type. Contravariance, counter-intuitively, allows you to use a more generic type, where a more derived type is specified. See also https://msdn.microsoft.com/en-us/library/dd799517.aspx

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());

这篇关于协方差和逆变现实世界的例子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆