Created
October 14, 2022 14:57
-
-
Save nomyfan/5ff3fe5fe9f812a67393bbabfe5bacbd to your computer and use it in GitHub Desktop.
Covariant vs. Contravariant
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Reflection.Metadata.Ecma335; | |
namespace CovariantContravariant | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
IContravariant<string> icos = new Contravariant<string>(); | |
IContravariant<object> icoo = new Contravariant<object>(); | |
// 因为IContravariant<object>的object是出现在入参里,约定的是入参必须是object派生。 | |
// 此时是作为消费者,使用IContravariant的角色充当生成者。 | |
// 生成者提供string类型数据,满足消费者的需求。 | |
icos = icoo; | |
ICovariant<string> icovs = new Covariant<string>(); | |
ICovariant<object> icovo = new Covariant<object>(); | |
// 因为ICovariant<string>的string是出现在返回值里,约定的是返回值必须是object的派生。 | |
// 此时是作为生成者,在使用ICovariant的角色充当消费者。 | |
// 生成者提供string类型数据,满足消费者需求。 | |
icovo = icovs; | |
} | |
} | |
interface IContravariant<in T> | |
{ | |
public void PutIn(T value); | |
} | |
interface ICovariant<out T> | |
{ | |
public T Result(); | |
} | |
public class Contravariant<T> : IContravariant<T> | |
{ | |
public void PutIn(T lst) | |
{ | |
Console.WriteLine(lst.ToString()); | |
} | |
} | |
public class Covariant<T> : ICovariant<T> | |
{ | |
public T Result() | |
{ | |
return default; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment