Ejemplo n.º 1
0
        static void Main(string[] args)
        {
            #region 泛型调用
            //泛型委托
            InputGenericsDelegate <int> inputGenericsDelegate = (p) => { Console.WriteLine("泛型委托"); };

            //泛型类
            MyGenerics <string> myGenerics = new MyGenerics <string>();

            //泛型方法
            myGenerics.GenericsMethod <string>("泛型方法");
            myGenerics.GenericsMethod <string, int>("泛型方法");
            #endregion

            #region 泛型可变性
            //协变
            CovariantDelegate <string> covariantDelegateStr = () => { return("协变泛型委托"); };
            CovariantDelegate <object> covariantDelegate    = covariantDelegateStr;

            //逆变
            ContravariantDelegate <object> contravariantDelegateObj = (p) => { Console.WriteLine("逆变泛型委托"); };
            ContravariantDelegate <string> contravariantDelegate    = contravariantDelegateObj;
            #endregion

            Console.ReadKey();
        }
Ejemplo n.º 2
0
        public void Test1()
        {
            MyGenerics g = new MyGenerics();

            int x = 5, y = 4;

            g.GetSum <int>(ref x, ref y);

            string strX = "5", strY = "4";

            g.GetSum(ref strX, ref strY);

            // Use the generic struct
            Rectangle <int> rec1 = new Rectangle <int>(20, 50);

            Console.WriteLine(rec1.GetArea());

            Rectangle <string> rec2 = new Rectangle <string>("20", "50");

            Console.WriteLine(rec2.GetArea());

            // Delegates allow you to reference methods
            // inside a delegate object. The delegate
            // object can then be passed to other
            // methods that can call the methods assigned
            // to the delegate. It can also stack methods
            // that are called in the specified order

            // Create delegate objects
            Arithmetic add, sub, addSub;

            // Assign just the Add method
            add = new Arithmetic(Add);

            // Assign just the Subtract method
            sub = new Arithmetic(Subtract);

            // Assign Add and Sub
            addSub = add + sub;

            // You could also subtract a method
            // sub = addSub - add;

            // Print out results
            Console.WriteLine($"Add {6} & {10}");
            add(6, 10);

            // Call both methods
            Console.WriteLine($"Add & Subtract {10} & {4}");
            addSub(10, 4);

            Console.ReadLine();
        }