标签:string 逆变 误解 class Person IComparable 协变 Programmer public
IComparable doesn't need to be contravariant?
In the code below i am targetting the .NET 2.0 Framework.
I can pass a Programmer (derived) object to the Compare method which expects a Person (base class)
But since a Programmer IS A Person (simple OO concept) i claim that in .NET 4.0 the 'in' keyword in the IComparable interface declaration is 'overkill' :)
Before i write an email to Microsoft about them removing the in keyword please try to convince me otherwise :)
class Program
{
static void Main(string[] args)
{
var person = new Person();
var test = person.CompareTo(new Programmer());
}
}
internal class Person : IComparable<Person>
{
public int Id { get; set; }
public string Name { get; set; }
public int CompareTo(Person other)
{
return this.Id - other.Id;
}
}
class Programmer : Person
{
public string ProgrammingLanguage { get; set; }
}
回答
Co- and contravariance is not about the types you pass into the methods. It is about the generic interfaces that contain the methods.
With in
the following code is legal:
IComparable<Person> foo = ...;
IComparable<Programmer> bar = foo;
Without the in
it would be illegal.
标签:string,逆变,误解,class,Person,IComparable,协变,Programmer,public 来源: https://www.cnblogs.com/chucklu/p/13755756.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。