Пример #1
0
        static void Main(string[] args)
        {
            VoidDelegate <int>    var1 = Void2;
            VoidDelegate <double> var2 = Void3;
            VoidDelegate <string> var3 = Void4;

            VoidDelegate <int, double, string> var6 = Void6;
            VoidDelegate <string, double, int> var7 = Void7;
            VoidDelegate <int, int, int>       var8 = Void8;

            ReturnDelegate <int, int>       var9  = Return2;
            ReturnDelegate <double, string> var10 = Return3;
            ReturnDelegate <string, double> var11 = Return4;


            ReturnDelegate <int, double, string, char> var12 = Return6;
            ReturnDelegate <string, double, int, long> var13 = Return7;
            ReturnDelegate <int, int, int, byte>       var14 = Return8;

            PredicateDelegate <int> var15 = BoolMethod1;

            PredicateDelegate <string> var16 = BoolMethod2;
            PredicateDelegate <double> var17 = BoolMethod3;
            PredicateDelegate <byte>   var18 = BoolMethod4;
        }
Пример #2
0
        public static void SingleAndMulticastExample()
        {
            VoidDelegate voidSingleDelegate = Log;

            VoidDelegate voidMultipleDelegate = Log;

            voidMultipleDelegate += LogSum;
            //voidMultipleDelegate = voidMultipleDelegate + LogSum;

            ReturnDelegate returnSingleDelegate = Mult;

            ReturnDelegate returnMultipleDelegate = Mult;

            returnMultipleDelegate += Minus;

            voidSingleDelegate(1, 2);
            Console.WriteLine();

            voidMultipleDelegate(2, 3);
            Console.WriteLine();

            var resultSingleDelegate = returnSingleDelegate(10, 5);

            Console.WriteLine($"resultSingleDelegate = {resultSingleDelegate}");
            Console.WriteLine();

            var resultMultipleDelegate = returnMultipleDelegate(23, 13);

            Console.WriteLine($"resultMultipleDelegate = {resultMultipleDelegate}");
        }
Пример #3
0
        public void FindOne(ReturnDelegate returnDelegate, string query)
        {
            String      connection = "mongodb://localhost";
            MongoClient client     = new MongoClient(connection);
            var         database   = client.GetDatabase(Database);
            var         collection = database.GetCollection <BsonDocument>(Collection);

            var projection = Builders <BsonDocument> .Projection.Exclude("_id").Include("section_texts");

            var filter = Builders <BsonDocument> .Filter.Eq("title", "Alabama");

            var document = collection.Find(filter).Project(projection).FirstOrDefault();

            if (document == null)
            {
                Console.WriteLine("Article not found");
            }
            else
            {
                string output = "";
                foreach (var value in document.Values)
                {
                    output += value.ToString();
                }

                output = output.TrimStart(new char[] { '[', '\n' });
                output = output.TrimEnd(new char[] { ']', '\n' });

                returnDelegate(output);
            }
        }
Пример #4
0
 public PendingCall(uint callId, Registry.RegisteredCall call, ReturnDelegate onReturn, ExceptionDelegate onException, Timer interval)
 {
     CallId      = callId;
     Call        = call;
     OnReturn    = onReturn;
     OnException = onException;
     Interval    = interval;
 }
Пример #5
0
        public ObjectPool(ReturnDelegate <object> createObjectMethod, int count = 32)
        {
            CreateInstanceMethod = createObjectMethod;
            if (createObjectMethod == null)
            {
                throw new ArgumentNullException("createObjectMethod cannot be null.");
            }

            Init(count);
        }
Пример #6
0
        public void PointerMethodDelegateReturn(int value)
        {
            var            obj         = new PointerHolder();
            ReturnDelegate d           = obj.Return;
            object         actualValue = d.DynamicInvoke(value);

            Assert.IsType <Pointer>(actualValue);
            void *actualPointer = Pointer.Unbox(actualValue);

            Assert.Equal(value, unchecked ((int)actualPointer));
        }
Пример #7
0
        static void Main(string[] args)
        {
            Action <int []> sortArr;

            Action <string>          action;
            Func <int, string>       myFunk;
            ReturnDelegate <MyClass> returnDelegate
                = MyClass.returnGeneric;

            // MyDelegate myDelegate = null;
            // int t = 5;
            // Console.WriteLine("Enter the number");
            // int answer =
            // Convert.ToInt32(Console.ReadLine());
            // switch(answer)
            // {
            //     case 1:
            //         myDelegate =
            //         MyClass.increment;
            //         break;
            //     case 2:
            //         myDelegate =
            //         MyClass.decrement;
            //         break;
            //     case 3:
            //         myDelegate =
            //         MyClass.increment;
            //         myDelegate +=
            //         MyClass.decrement;
            //         break;
            // }

            // myDelegate(ref t);
            // System.Console.WriteLine(t);
            // if(answer == 3)
            // {
            //     myDelegate -= MyClass.decrement;
            // }
            // myDelegate(ref t);
            // System.Console.WriteLine(t);

            // System.Console.WriteLine
            // (returnDelegate(new MyClass()));

            myFunk = MyClass.myFunc;
            System.Console.WriteLine(myFunk(5));
            action = MyClass.Message;
            action("dsdds");

            sortArr  = MyClass.ascSort;
            sortArr += MyClass.descSort;

            sortArr(new int [] { 6, 2, 8, 1, 10, 20, 55 });
        }
Пример #8
0
        static void Main(string[] args)
        {
            ReturnDelegate returnDelegate = test1;

            returnDelegate += test2;

            //----------------------------------------------------------
            foreach (var del in returnDelegate.GetInvocationList())//这是可以全部输出返回值的操作
            {
                Console.WriteLine(del.DynamicInvoke());
            }
            Console.ReadKey();
        }
Пример #9
0
        private object BlockingInvoke(ReturnDelegate del)
        {
            // Fire off the asynchronous operation
            MessageQueue.BlockingMessage message = new MessageQueue.BlockingMessage(del);
            mMessageQueue.Push(message);
            mHostEvent.Set();

            // Wait for it to finish
            message.AsyncWaitHandle.WaitOne();

            // Return the result, or re-throw the exception
            if (message.Exception != null)
            {
                throw (message.Exception);
            }
            else
            {
                return(message.Result);
            }
        }
Пример #10
0
        /// <summary>
        /// Send a call to the server
        /// </summary>
        /// <param name="type">The call type (must have been registered with Registry.RegisterClientCall)</param>
        /// <param name="data">The data pack to send</param>
        /// <param name="onReturn">The callback to be executed when the server answers this call</param>
        /// <param name="onException">The callback to be executed when the server answer this call with an exception (or the call timeouts or the connection closes)</param>
        /// <param name="timeout">The timeout (in ms), 0 means no timeout</param>
        public void SendCall(uint type, Data data, ReturnDelegate onReturn = null, ExceptionDelegate onException = null, int timeout = 60000)
        {
            // Validate the data
            if (!IsReady)
            {
                throw new InvalidOperationException("The connection has already been closed");
            }
            Registry.RegisteredCall call = Registry.GetClientCall(type);
            if (call == null)
            {
                throw new ArgumentException("Invalid call type " + type);
            }
            if (data.Format != call.ArgsFormat.FormatString)
            {
                throw new ArgumentException("Invalid data type '" + data.Format + "' for call " + type);
            }

            // Create the meta-data
            byte[] binData   = data.GetBytes();
            byte[] binMeta   = new Data().AddUint(type).AddUint(++LastSentId).GetBytes();
            byte[] binLength = new Data().AddUint((ulong)(binData.Length + binMeta.Length)).GetBytes();

            // Send the call
            Socket.Write(binLength);
            Socket.Write(binMeta);
            Socket.Write(binData);

            // Set timeout
            Timer interval = null;

            if (timeout != 0)
            {
                interval           = new Timer(timeout);
                interval.AutoReset = false;
                interval.Elapsed  += TimeoutCallback;
                interval.Start();
            }

            // Save info about the sent call
            PendingCalls.AddLast(new PendingCall(LastSentId, call, onReturn, onException, interval));
        }
Пример #11
0
 public PendingCall(uint callId, Registry.RegisteredCall call, ReturnDelegate onReturn, ExceptionDelegate onException, Timer interval)
 {
     CallId = callId;
     Call = call;
     OnReturn = onReturn;
     OnException = onException;
     Interval = interval;
 }
Пример #12
0
        /// <summary>
        /// Send a call to the server
        /// </summary>
        /// <param name="type">The call type (must have been registered with Registry.RegisterClientCall)</param>
        /// <param name="data">The data pack to send</param>
        /// <param name="onReturn">The callback to be executed when the server answers this call</param>
        /// <param name="onException">The callback to be executed when the server answer this call with an exception (or the call timeouts or the connection closes)</param>
        /// <param name="timeout">The timeout (in ms), 0 means no timeout</param>
        public void SendCall(uint type, Data data, ReturnDelegate onReturn = null, ExceptionDelegate onException = null, int timeout = 60000)
        {
            // Validate the data
            if (!IsReady)
                throw new InvalidOperationException("The connection has already been closed");
            Registry.RegisteredCall call = Registry.GetClientCall(type);
            if (call == null)
                throw new ArgumentException("Invalid call type " + type);
            if (data.Format != call.ArgsFormat.FormatString)
                throw new ArgumentException("Invalid data type '" + data.Format + "' for call " + type);

            // Create the meta-data
            byte[] binData = data.GetBytes();
            byte[] binMeta = new Data().AddUint(type).AddUint(++LastSentId).GetBytes();
            byte[] binLength = new Data().AddUint((ulong)(binData.Length + binMeta.Length)).GetBytes();

            // Send the call
            Socket.Write(binLength);
            Socket.Write(binMeta);
            Socket.Write(binData);

            // Set timeout
            Timer interval = null;
            if (timeout != 0) {
                interval = new Timer(timeout);
                interval.AutoReset = false;
                interval.Elapsed += TimeoutCallback;
                interval.Start();
            }

            // Save info about the sent call
            PendingCalls.AddLast(new PendingCall(LastSentId, call, onReturn, onException, interval));
        }
Пример #13
0
		private object BlockingInvoke(ReturnDelegate del)
		{
			// Fire off the asynchronous operation
			MessageQueue.BlockingMessage message = new MessageQueue.BlockingMessage(del);
			mMessageQueue.Push(message);
			mHostEvent.Set();

			// Wait for it to finish
			message.AsyncWaitHandle.WaitOne();

			// Return the result, or re-throw the exception
			if (message.Exception != null)
				throw (message.Exception);
			else
				return message.Result;
		}
Пример #14
0
        static void Main(string[] args)
        {
            //Single cast Delegate explanation//
            Console.BackgroundColor = ConsoleColor.Cyan;
            Console.ForegroundColor = ConsoleColor.DarkRed;
            Console.WriteLine("******Single Cast with Basic Explanation********");
            Console.ResetColor();
            SingleCastDelegate sobj = new SingleCastDelegate();
            AddDelegate        ad   = sobj.Add;

            ad.Invoke(100, 100);
            GreetingsMessage gd = new GreetingsMessage(SingleCastDelegate.Greetings);
            // GreetingsMessage gd = new GreetingsMessage(SingleCastDelegate.Greetings);
            string name = gd.Invoke("Limon");

            Console.WriteLine(name);

            //Multicast Basic explanation//
            Console.BackgroundColor = ConsoleColor.Cyan;
            Console.ForegroundColor = ConsoleColor.DarkRed;
            Console.WriteLine("******Multicast with Basic Explanation********");
            Console.ResetColor();
            Multicast    obj    = new Multicast();
            MathDelegate md     = Multicast.Add;
            MathDelegate mdSub  = Multicast.Sub;
            MathDelegate mdMul  = obj.Mul;
            MathDelegate mdDiv  = obj.Div;
            MathDelegate mainMd = md + mdSub + mdMul + mdDiv;

            mainMd.Invoke(10, 10);
            mainMd -= mdSub;
            Console.WriteLine($"After removing {mdSub}");
            mainMd.Invoke(20, 50);

            //Multicast with return type//
            Console.BackgroundColor = ConsoleColor.Cyan;
            Console.ForegroundColor = ConsoleColor.DarkRed;
            Console.WriteLine("******Multicast with return type********");
            Console.ResetColor();
            // ReturnType rt = new ReturnType();
            ReturnDelegate rd = ReturnType.Method1;

            rd += ReturnType.Method2;
            int valueGet = rd();

            Console.WriteLine("Return Value:{0}", valueGet);

            Console.BackgroundColor = ConsoleColor.Cyan;
            Console.ForegroundColor = ConsoleColor.DarkRed;
            Console.WriteLine("******Multicast with Out type********");
            Console.ResetColor();

            ReturnDelegateOUt rdo = ReturnType.OutMethod1;

            rdo += ReturnType.OutMethod2;
            int    IdFromOut       = -1;
            string UserNameFromOut = null;

            rdo(out IdFromOut, out UserNameFromOut);
            Console.WriteLine($"Value from Output parameter Id: {IdFromOut} Name:{UserNameFromOut}");

            //
            Console.BackgroundColor = ConsoleColor.Cyan;
            Console.ForegroundColor = ConsoleColor.DarkRed;
            Console.WriteLine("******Multicast with RealLife example********");
            Console.ResetColor();
            Employee emp1 = new Employee()
            {
                ID         = 101,
                Name       = "Pranaya",
                Gender     = "Male",
                Experience = 5,
                Salary     = 10000
            };
            Employee emp2 = new Employee()
            {
                ID         = 102,
                Name       = "Priyanka",
                Gender     = "Female",
                Experience = 10,
                Salary     = 20000
            };
            Employee emp3 = new Employee()
            {
                ID         = 103,
                Name       = "Anurag",
                Experience = 15,
                Salary     = 30000
            };
            List <Employee> listEmployess = new List <Employee>()
            {
                emp1, emp2, emp3
            };

            // EligibleToPromotion eligbleDelegate = Employee.Promote;

            //Employee.PromoteEmployee(listEmployess, eligbleDelegate);
            Employee.PromoteEmployee(listEmployess, x => x.Salary >= 10000);
        }
Пример #15
0
        public ObjectPool(ReturnDelegate <T> createObjectMethod, int count = 32)
        {
            CreateInstanceMethod = createObjectMethod;

            Init(count);
        }