栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

协方差和反方差的真实世界示例

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

协方差和反方差的真实世界示例

假设您有一个Person类和一个从其派生的类Teacher。您有一些操作以a

IEnumerable<Person>
作为参数。在您的School课堂中,您有一个返回的方法
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 typemailingList.Add(teachers);// the Set<T> constructor uses a contravariant interface, IComparer<in T>,// we can use a more generic type than required.// See https://msdn.microsoft.com/en-us/library/8ehhxeaf.aspx for declaration syntaxvar teacherSet = new SortedSet<Teachers>(teachers, new PersonNameComparer());


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/597019.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号