xiaolizi007
2/20/2017 - 12:39 PM

Ref Demo

逆变协变 #csharp

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RefApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            int i = 10;
            Person a = new Person(ref i);
            Console.WriteLine(i);
            Console.ReadKey();
        }
    }
    class Person
    {
        public Person(ref int age)
        {
            age = age + 1;
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OutCovariantDemo
{
    // Covariant interface. 协变接口
    interface ICovariant<out R> { }

    // Extending covariant interface.扩展协变接口
    interface IExtCovariant<out R> : ICovariant<R> { }

    // Implementing covariant interface.实现协变接口
    class Sample<R> : ICovariant<R> { }

    class Program
    {
        static void Test()
        {
            ICovariant<Object> iobj = new Sample<Object>();
            ICovariant<String> istr = new Sample<String>();

            // You can assign istr to iobj because
            // the ICovariant interface is covariant.
            //协变泛型对象
            iobj = istr;
        }
    }
}
  class OutDemo
    {
        static void Method(out int i)
        {
            i = 44;
        }
        static void Main()
        {
            int value;
            Method(out value);
            // value is now 44
        }
    }
  // Contravariant interface.
    interface IContravariant<in A> { }

    // Extending contravariant interface.
    interface IExtContravariant<in A> : IContravariant<A> { }

    // Implementing contravariant interface.
    class Sample<A> : IContravariant<A> { }

    class Program
    {
        static void Test()
        {
            IContravariant<Object> iobj = new Sample<Object>();
            IContravariant<String> istr = new Sample<String>();

            // You can assign iobj to istr because
            // the IContravariant interface is contravariant.
            istr = iobj;
        }
    }