您的位置:首页 > 其它

协变与逆变

2016-07-27 11:18 148 查看
协变:将子类泛型集合赋值给父类的泛型集合

逆变:将父类的泛型集合赋值给子类的泛型集合

  class Program

    {

        static void Main(string[] args)

        {

            #region 协变  

            Func<decimal, employee> child = (target) => { var employee = new employee(); employee.money = 10000; return employee; };

            Func<decimal, person> per = (target) => { return new employee(); };

            per = child;//协变 将子类泛型集合赋值给父类的泛型集合

            #endregion

            #region 逆变

            Action<person> parent = Contacts;

            Action<employee> emp = Contacts;

            emp = parent;//逆变 将父类的泛型集合赋值给子类的泛型集合

            Action<object> obj = (target) => { Console.WriteLine(target.GetType().Name); };

            Action<employee> epl = obj; //逆变 将父类的泛型集合赋值给子类的泛型集合

            #endregion

            

        }

        static void Contacts(person per) { }

    }

    public class person { }

    public class employee : person {

        public decimal money { set; get; }

    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: