using System;using System.Collections.Generic; class MainClass{ static void Main() { object o1 = "";//类型安全 string s1 = (string)o1;//非类型安全 IEnumerable o2 = new List();//协变 Action s2 = new Action((o) => { });//逆变 }}
六:自定义协变
using System;using System.Collections.Generic; class MainClass{ static void Main() { ICustomCovariant o = new CustomCovariant(); }} public interface ICustomCovariant{ T Get();}public class CustomCovariant< T> : ICustomCovariant{ public T Get() { return default(T); }}
七:自定义逆变
using System;using System.Collections.Generic; class MainClass{ static void Main() { IContravariant o = new CustomContravariant(); }} public interface IContravariant{ void Get(T t);}public class CustomContravariant : IContravariant{ public void Get(T t) { }}