Exemplo n.º 1
0
        static void Main(string[] args)
        {
            // 1. 기본 선언
            DelegateTest dt = new DelegateTest(Sum);

            // 2. 간략한 선언
            DelegateTest dt2 = Sum;

            // 3. 익명 함수 선언
            DelegateTest dt3 = delegate(int a, int b)
            {
                Console.WriteLine("a + b = " + (a + b));
            };

            // 4. 람다식 선언
            DelegateTest dt4 = (a, b) =>
            {
                Console.WriteLine("a + b = " + (a + b));
            };

            dt(1, 1);
            dt2(2, 2);
            dt3(3, 3);
            dt4(4, 4);
        }
Exemplo n.º 2
0
    static void Main()
    {
        PrintMeInfo info = null;

        info += new PrintMeInfo(ShowMeTheNumber);
        info += new PrintMeInfo(DelegateTest.IsOdd);
        info += new PrintMeInfo(IsDividableByTen);

        DelegateTest additional_info = new DelegateTest();

        info += new PrintMeInfo(additional_info.BiggerThanTen); //The method is not static!

        Calculations calc = null;

        calc += new Calculations(DelegateTest.SumAndMultiply1);
        calc += new Calculations(DelegateTest.SumAndMultiply2);

        List <Calculations> my_list = new List <Calculations> {
            SumAndMultiply1, SumAndMultiply2, SumAndMultiply3
        };

        foreach (var my_result in my_list)
        {
            Console.WriteLine(my_result(5, 6, 7));
        }

        info(25);
    }
Exemplo n.º 3
0
        // Firma de un metodo/funcion
        static void AnonymousSample()
        {
            // Declaracion normal
            // Type nombre;
            Type   a1;
            string a2;
            int    a3;

            // Declaracion anonima
            var b1 = typeof(object);
            var b2 = "Hola";
            var b3 = 10;

            // no funciona
            // var b4;



            // Delegates examples

            // Function call
            Console.WriteLine(Sumar(2, 3));

            Calculo funcion = Sumar;

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

            DelegateTest x = new DelegateTest();

            x.ClickHandler += Sumar;
            x.ClickHandler += Restar;
            x.ClickHandler += (z, y) => { return(10); };
        }
Exemplo n.º 4
0
        public void DelegatePracticeMethodGroupConversion()
        {
            // Construct a delegate using method group conversion.
            StrMod strOp = DelegateTest.ReplaceSpaces; // use method group conversion
            string str;

            // Call methods through the delegate.
            str = strOp("This is a test.");
            Console.WriteLine("Resulting string: " + str);
            Console.WriteLine();
            strOp = DelegateTest.RemoveSpaces; // use method group conversion
            str   = strOp("This is a test.");
            Console.WriteLine("Resulting string: " + str);
            Console.WriteLine();
            strOp = DelegateTest.Reverse; // use method group conversion
            str   = strOp("This is a test.");
            Console.WriteLine("Resulting string: " + str);
            // Calling Intance Class
            Console.WriteLine("Delegate  Method Group Conversion with Intance Method");
            DelegateTest DlgOb = new DelegateTest();

            strOp = DlgOb.ReplaceSpacesInsTanceMethod;
            str   = strOp("My name is Muhammad Adshikuzzaman");

            Console.CursorSize = 10;
            Console.WriteLine("My space replaced name is : " + str);
            Console.WriteLine();
        }
Exemplo n.º 5
0
        private void btnDelegateTestClick(object sender, EventArgs e)
        {
            //使用using在调用完后会自动回收垃圾
            using (DelegateTest test = new DelegateTest())
            {
                //实例化委托
                DelegateTest.StringDelegate dgt1 = new DelegateTest.StringDelegate(doubleString);
                dgt1 += plusA2String;

                // 用这个变量来保存输出的字符串
                StringBuilder returnstring = new StringBuilder();

                //以下方法可获取委托中每个方法的返回值,并可处理委托链中的报错
                // 获取一个委托数组,其中每个元素都引用链中的委托
                foreach (var item in dgt1.GetInvocationList())
                {
                    DelegateTest.StringDelegate tempObj = item as DelegateTest.StringDelegate;
                    try
                    {
                        string str = "test\n";
                        //调用委托获得返回值
                        returnstring.Append(tempObj(ref str) + Environment.NewLine);
                    }
                    catch (Exception ex)
                    {
                        returnstring.AppendFormat("异常从 {0} 方法中抛出, 异常信息为:{1}{2}", tempObj.Method.Name, ex.Message, Environment.NewLine);
                    }
                }

                richTextBox2.Text += returnstring;
                richTextBox2.Text += "///////////////////////////////////////\n";
                richTextBox2.Text += test.delegateUser("test\n", dgt1) + "\n";
            }
        }
Exemplo n.º 6
0
    public Object TestConv(int a, int b)
    {
        int[]        arr = new int[1];
        DelegateTest dt  = new DelegateTest();

        this.Prop = dt;
        this[0]   = dt;
        arr[0]    = dt;
        DelegateTest v = this.Prop;
        DelegateTest v2 = this[0];
        DelegateTest v3 = arr[0];
        DelegateTest vv, vv2, vv3;

        vv  = this.Prop;
        vv2 = this[0];
        vv3 = arr[0];
        DelegateTest v4 = arr[0];

        int[] arr2 = null;
        v4 = arr2?[0];
        DelegateTest vv4 = arr2?[0];
        ConvTest     ct  = null;

        dt = ct?.Prop;
        dt = ct?[0];
        DelegateTest v5 = ct?[0];
        DelegateTest vv5;

        vv5 = ct?[0];
        return(null);
    }
Exemplo n.º 7
0
        static void Main(string[] args)
        {
            // 创建委托对象1,绑定一个静态方法
            DelegateTest dtstatic = new DelegateTest(methodStatic);
            // 创建委托对象2,绑定一个实例方法
            DelegateTest dtinstance = new DelegateTest(new Captal8_Delegate_04DelegateChain().methodInstance);

            // 创建一个委托对象,并绑定委托对象1,使用"+"添加委托对象2,成为委托链
            DelegateTest delegateChain = dtstatic;

            delegateChain += dtinstance;

            // 调用委托对象
            delegateChain.Invoke();

            Console.WriteLine();
            Console.WriteLine("从委托链上移除静态方法后:");

            // 从委托链上移除静态方法
            delegateChain -= dtstatic;

            delegateChain.Invoke();

            Console.ReadKey();
        }
Exemplo n.º 8
0
        public delegate void DelegateTest(); // 声明一个委托类型

        public static void Show()
        {
            DelegateTest dt_static   = new DelegateTest(Method1);                     // 用静态方法来实例化委托 dt_static
            DelegateTest dt_instance = new DelegateTest(new DelegateChain().Method2); // 用实例方法来实例化委托 dt_instance

            // 定义一个委托对象, 一开始初始化为null, 没有和任何方法关联
            DelegateTest delegate_chain = null; // 初始化不是必须的

            // 使用 + 号链接委托, 多个委托链接起来形成委托链
            delegate_chain = dt_static + dt_instance;

            /* 显然, 使用符合赋值 += 符号亦可
             * delegate_chain += dt_static;
             * delegate_chain += dt_instance;
             */

            // 调用委托链
            delegate_chain();

            // 使用 - 或 -= 取消链接委托
            delegate_chain -= dt_static;
            delegate_chain();

            // 委托链可以重新赋值
            delegate_chain = dt_static;
            delegate_chain();
        }
Exemplo n.º 9
0
        public static void Main()
        {
            InterfaceTest interfaceTest = new InterfaceTest();
            DelegateTest  delegateTest  = new DelegateTest();

            interfaceTest.Run();
            delegateTest.Run();
        }
            static void Main(string[] args)
            {
                Console.WriteLine(math.Add("4", "9"));

                Console.ReadKey();

                DelegateTest a1 = Add;

                a1(14, 32);
            }
Exemplo n.º 11
0
    static void Main()
    {
        FirstDelegate d1       = new FirstDelegate(StaticMethod);
        DelegateTest  instance = new DelegateTest();

        instance.name = "My instance";
        FirstDelegate d2 = new FirstDelegate(instance.InstanceMethod);

        Console.WriteLine(d1(10)); // Writes out "Static method: 10"
        Console.WriteLine(d2(5));  // Writes out "My instance: 5"
    }
Exemplo n.º 12
0
        static void Main(string[] args)
        {
            DelegateTest delegatetest = new DelegateTest();

            delegatetest.DoStuff();


            DoOperation someOperation = new DoOperation(MyMultiply);

            someOperation += MySum;
        }
Exemplo n.º 13
0
        static void Main()
        {
            // 간단 사용법 (그냥 메소드 호출이랑 차이없음)
            DelegateTest AddDelegate = new DelegateTest(Add);
            int          sumValue    = AddDelegate(5, 10);

            Console.WriteLine(sumValue);

            // 콜백 예제 10+입력받은값 출력
            CallbackDelegate readText = new CallbackDelegate(ReturnInt);

            PrintSum(10, readText);
        }
Exemplo n.º 14
0
    // Start is called before the first frame update
    void Start()
    {
        DelegateTest delTest = FindObjectOfType <DelegateTest>();

        if (delTest != null)
        {
            delTest.OnSpacePressed += Testing_OnSpacePressed;
        }
        else
        {
            Debug.Log("Could not find DelegateTest.");
        }
    }
Exemplo n.º 15
0
        static void Main(string[] args)
        {
            //Multicast delegate
            DelegateTest dt = () => { };

            dt  = T1;
            dt += T2;
            dt += T3;
            dt += T4;
            dt();

            Console.ReadLine();
        }
        public static void Run()
        {
            string       mid     = ",middle part,";
            DelegateTest anondel = delegate(string param)
            {
                param += mid;
                param += " and this was added to the string.";
                return(param);
            };

            Console.WriteLine();
            Console.WriteLine("AnonymousDelegate");
            Console.WriteLine(anondel("start of string."));
        }
Exemplo n.º 17
0
        public void DelegatePracticeWithInstanceMthod()
        {
            // Construct a delegate.
            StrMod strOp = new StrMod(DelegateTest.ReplaceSpaces);
            string str;
            // Calling Intance Class

            DelegateTest DlgOb = new DelegateTest();

            strOp = new StrMod(DlgOb.ReplaceSpacesInsTanceMethod);
            str   = strOp("My name is Muhammad Adshikuzzaman");

            Console.CursorSize = 10;
            Console.WriteLine("My space replaced name is : " + str);
            Console.WriteLine();
        }
Exemplo n.º 18
0
        static void Main(string[] args)
        {
            DelegateTest del1 = Test1;

            // 多播委托
            del1 += Test2;
            del1 += Test3;
            del1 += Test4;
            del1();
            Console.WriteLine("~~~~~~~~~~~~~~~");
            del1 -= Test4;
            del1 -= Test3;

            del1();

            Console.ReadKey();
        }
Exemplo n.º 19
0
    public Chapter1()
    {
        var delegObj = new DelegateTest();
        string str;

        var strOp = new StrMod(delegObj.ReplaceSpaces);
        str = strOp("Test string line");
        Console.WriteLine("str: " + str + "\n");

        strOp = delegObj.RemoveSpace;
        str = strOp("Test string line");
        Console.WriteLine("str: " + str + "\n");

        strOp = delegObj.Reverse;
        str = strOp("Test string line");
        Console.WriteLine("str: " + str + "\n");
    }
Exemplo n.º 20
0
        public void CanRegisterAndResolveServiceWithRuntimeTypeAndMetadata()
        {
            // Arrange
            _containerBuilder.ForType <IMyInterface>(typeof(MyClassImplementingInterfaceWithMetadata))
            .Register()
            .WithMetadata <IMyMetadata, string>(a => a.StringValue, "sdasdasd")
            .WithMetadata <IMyMetadata, Guid>(a => a.GuidValue, Guid.NewGuid())
            .WithMetadata <IMyMetadata, int>(a => a.IntValue, 1237);

            _containerBuilder.ForType <IMyInterface>(typeof(MyClassImplementingInterfaceWithMetadata))
            .Register()
            .WithMetadata <IMyMetadata, string>(a => a.StringValue, "blahblah")
            .WithMetadata <IMyMetadata, Guid>(a => a.GuidValue, Guid.Empty)
            .WithMetadata <IMyMetadata, int>(a => a.IntValue, 7);

            DelegateTest delegateTest = new DelegateTest();

            delegateTest.GetGuid = Guid.NewGuid();
            var blahblah2 = "blahblah2";

            delegateTest.GetString = blahblah2;
            delegateTest.GetInt    = 42;

            _containerBuilder.ForType <IMyInterface>(typeof(MyClassImplementingInterfaceWithMetadata))
            .Register()
            .WithMetadata <IMyMetadata, string>(a => a.StringValue, delegateTest.GetString)
            .WithMetadata <IMyMetadata, Guid>(a => a.GuidValue, delegateTest.GetGuid)
            .WithMetadata <IMyMetadata, int>(a => a.IntValue, delegateTest.GetInt);

            delegateTest.GetGuid = Guid.Empty;

            _containerBuilder.ForType <MyClassAcceptingResolvedMetadata, MyClassAcceptingResolvedMetadata>().Register();

            IDependencyResolver container = _containerBuilder.Build();

            // Act
            var result         = container.Resolve <IMyInterface>();
            var autoResult     = container.Resolve <MyClassAcceptingResolvedMetadata>();
            var propertyResult = result.MyStringProperty;

            // Assert
            Assert.IsNotNull(result);
            Assert.IsNotNull(autoResult);
            Assert.IsInstanceOfType(result, typeof(IMyInterface));
            Assert.IsTrue(propertyResult == blahblah2);
        }
Exemplo n.º 21
0
        public void VisitControls(ControlCollection list, DelegateTest isTarget, ControlDelegate visit)
        {
            foreach (Control member in list)
            {
                if (member.HasControls())
                {
                    VisitControls(member.Controls,
                                  isTarget,
                                  visit
                                  );
                }

                if (isTarget(member))
                {
                    visit(member);
                }
            }
        }
Exemplo n.º 22
0
        public void CanRegisterAndResolveServiceWithRuntimeTypeAndMetadata()
        {
            // Arrange
            _containerBuilder.ForType<IMyInterface>(typeof (MyClassImplementingInterfaceWithMetadata))
                .Register()
                .WithMetadata<IMyMetadata, string>(a => a.StringValue, "sdasdasd")
                .WithMetadata<IMyMetadata, Guid>(a => a.GuidValue, Guid.NewGuid())
                .WithMetadata<IMyMetadata, int>(a => a.IntValue, 1237);

            _containerBuilder.ForType<IMyInterface>(typeof(MyClassImplementingInterfaceWithMetadata))
                .Register()
                .WithMetadata<IMyMetadata, string>(a => a.StringValue, "blahblah")
                .WithMetadata<IMyMetadata, Guid>(a => a.GuidValue, Guid.Empty)
                .WithMetadata<IMyMetadata, int>(a => a.IntValue, 7);

            DelegateTest delegateTest = new DelegateTest();
            delegateTest.GetGuid = Guid.NewGuid();
            var blahblah2 = "blahblah2";
            delegateTest.GetString = blahblah2;
            delegateTest.GetInt = 42;

            _containerBuilder.ForType<IMyInterface>(typeof(MyClassImplementingInterfaceWithMetadata))
                .Register()
                .WithMetadata<IMyMetadata, string>(a => a.StringValue, delegateTest.GetString)
                .WithMetadata<IMyMetadata, Guid>(a => a.GuidValue, delegateTest.GetGuid)
                .WithMetadata<IMyMetadata, int>(a => a.IntValue, delegateTest.GetInt);

            delegateTest.GetGuid = Guid.Empty;

            _containerBuilder.ForType<MyClassAcceptingResolvedMetadata, MyClassAcceptingResolvedMetadata>().Register();

            IDependencyResolver container = _containerBuilder.Build();

            // Act
            var result = container.Resolve<IMyInterface>();
            var autoResult = container.Resolve<MyClassAcceptingResolvedMetadata>();
            var propertyResult = result.MyStringProperty;

            // Assert
            Assert.IsNotNull(result);
            Assert.IsNotNull(autoResult);
            Assert.IsInstanceOfType(result, typeof(IMyInterface));
            Assert.IsTrue(propertyResult == blahblah2);
        }
Exemplo n.º 23
0
        static void Main(string[] args)
        {
            // 创建委托实例
            NumberChanger nc1 = new NumberChanger(AddNum);
            NumberChanger nc2 = new NumberChanger(MultNum);

            // 使用委托对象调用方法
            nc1(25, "");
            Console.WriteLine("Value of Num: {0}", getNum());
            nc2(5, "");
            Console.WriteLine("Value of Num: {0}", getNum());

            StringChanger c = new StringChanger(addString);

            c("tema");
            Console.WriteLine(c("tema"));
            Console.ReadKey();

            //委托链
            //委托的多播(Multicasting of a Delegate)

            /*s
             * 委托对象可使用 "+" 运算符进行合并。一个合并委托调用它所合并的两个委托。只有相同类型的委托可被合并。"-" 运算符可用于从合并的委托中移除组件委托。
             * 使用委托的这个有用的特点,您可以创建一个委托被调用时要调用的方法的调用列表。这被称为委托的 多播(multicasting),也叫组播。下面的程序演示了委托的多播:
             * - 方法移除一个委托
             */
            DelegateTest test  = null;
            DelegateTest test1 = new DelegateTest(writeDown);
            DelegateTest test2 = new DelegateTest(writeDown);
            DelegateTest test3 = new DelegateTest(writeDown);
            DelegateTest test4 = new DelegateTest(writeDown);


            test += test1;
            test += test2;
            test += test3;
            test += test4;

            test -= test1;
            test("qwerty");


            Console.Read();
        }
Exemplo n.º 24
0
        static void Main(string[] args)
        {
            Console.WriteLine("\n\n---===Delegate===---\n");
            var instance = new MyClass();

            // Instantiate delegate with named methode:
            DelegateTest dt = instance.Average;


            // Invoke delegate:
            var numbers = new List <double>()
            {
                4, 2, 6
            };
            double averageOfThree = dt(numbers);

            Console.WriteLine("The average of the following set of numbers (2, 4, 6) is: {0}", averageOfThree);
            Console.ReadKey();

            dt -= instance.Average;
            dt += MyClass.PrintFirst;
            Console.WriteLine("First element: {0}", dt(numbers));
            Console.ReadKey();


            // Instantiate delegate with anonymous methode:
            DelegateTest dt2 = delegate(List <double> input)
            {
                return(input.Any() ? input.Sum() / input.Count() : 0);
            };

            double average = dt2(new List <double>()
            {
                2, 6, 8
            });

            Console.WriteLine("The average of the following set of numbers (2, 6, 8) is: {0}", average);

            /*
             * Instantiate delegate with lambda expression -> next day
             */

            Console.ReadKey();
        }
Exemplo n.º 25
0
    protected T CreateControl <T>(T prefab, string text) where T : Object, IControl
    {
        if (!prefab)
        {
            throw new Exception(String.Format("Отсутствует ссылка на {0}", typeof(T)));
        }
        var tempControl = Instantiate(prefab, Interface.InterfaceResources.MainPanel.transform.position, Quaternion.identity,
                                      Interface.InterfaceResources.MainPanel.transform);

        if (tempControl.GetText != null)
        {
            tempControl.GetText.text = text;
        }
        DelegateTestr = Test;

        var test = DelegateTestr.BeginInvoke(null, null);

        return(tempControl);
    }
Exemplo n.º 26
0
        /// <summary>
        /// 委托链
        /// </summary>
        public void T8D4()
        {
            //TODO:用静态方法实例化委托
            DelegateTest dtstatic   = new DelegateTest(T8.Method1);
            DelegateTest dtinstance = new DelegateTest(new T8().Method2);
            //TODO:定义一个委托,初始化为null,即不代表任何方法
            DelegateTest delegatechain = null;

            //TODO:使用“+”符号链接委托,链接多个委托后形成委托链
            delegatechain += dtstatic;
            delegatechain += dtinstance;
            //TODO:使用“-”符号把委托从委托链中移除
            delegatechain -= dtstatic;
            //TODO:调用委托链
            delegatechain();


            Console.Read();
        }
Exemplo n.º 27
0
        static void Run()
        {
            // TODO: One day these should be converted to proper unit tests...

            TestPrimitiveType();

            TestWithDispatch(new BaseClass());
            TestWithDispatch(new DerivedClassA());
            TestWithDispatch(new DerivedClassB());
            TestWithDispatch(new DerivedClassC());

            TreeTest.RunTest();
            TreeTest.RunTestWithDefinitions();

            TestArrays();

            TestManyTypes();

            DelegateTest.RunTest();
        }
Exemplo n.º 28
0
        //-----------------------------------------------------------------------------------------------------
        public static void LambadaDelegateEntry()
        {
            DateTime dt = DateTime.Now; TimeSpan dt1 = new TimeSpan();

            foreach (var item in Process.GetProcesses())
            {
                Console.WriteLine(item.ProcessName);
            }
            string       mid    = ",middle part,";
            DelegateTest lamdel = param => param += mid + " and this was added to the string.";

            //{
            //    param += mid;
            //    param += " and this was added to the string.";
            //    return param;
            //};
            Console.WriteLine(lamdel("start of string"));

            Console.WriteLine(Process.GetCurrentProcess().Threads[0].UserProcessorTime.Subtract(dt1).TotalMilliseconds);
        }
Exemplo n.º 29
0
        static void Main(string[] args)
        {
            // 用静态方法来实例化委托
            DelegateTest dtstatic = new DelegateTest(Program.method1);

            DelegateTest dtinstance = new DelegateTest(new Program().method2);

            // 定义一个委托对象,一开始初始化为null,就是不代表任何方法(我就是我,我不代表任何人)
            DelegateTest delegatechain = null;

            // 使用+符号链接委托,链接多个委托后就成为委托链了
            delegatechain += dtstatic;
            delegatechain += dtinstance;

            // 使用-运算符把dtstatic委托从委托链中移除
            delegatechain -= dtstatic;

            // 调用委托链
            delegatechain();
            Console.Read();
        }
        static void Main(string[] args)
        {
            // 用静态方法来实例化委托
            DelegateTest dtstatic = new DelegateTest(Program.method1);

            DelegateTest dtinstance = new DelegateTest(new Program().method2);

            // 定义一个委托对象,一开始初始化为null,就是不代表任何方法(我就是我,我不代表任何人)
            DelegateTest delegatechain = null;

            // 使用+符号链接委托,链接多个委托后就成为委托链了
            delegatechain += dtstatic;
            delegatechain += dtinstance;
            Console.WriteLine("delegatechain's number methods : " + delegatechain.GetInvocationList().Length);
            // 使用-运算符把dtstatic委托从委托链中移除
            delegatechain -= dtstatic;

            // 调用委托链
            delegatechain.Invoke();
            Console.Read();
        }
Exemplo n.º 31
0
        static void Main(string[] args)
        {
            #region DelegateTest
            DelegateTest d = new DelegateTest(Test);
            d("Delegate");

            //ラムダ1
            d = new DelegateTest((string s) => { Console.WriteLine($"This is {s}"); });
            d("Delegate");

            //ラムダ2
            d = new DelegateTest(s => Console.WriteLine($"This is {s}"));
            d("Delegate");
            #endregion

            #region Action
            Action <string> a = Test;
            a("Action");

            a = s => Console.WriteLine($"This is {s}");
            a("Action");
            #endregion

            #region Func
            Func <string> f = Test2;
            Console.WriteLine($"{f()} Func");

            f = () => "This is";//引数のないラムダ式は()を省略できない
            Console.WriteLine($"{f()} Func");

            Func <string, string> ff = Test3;
            Console.WriteLine(ff("Func"));

            ff = s => $"This is {s}";
            Console.WriteLine(ff("Func"));
            #endregion

            Console.ReadKey();
        }
Exemplo n.º 32
0
        static void Main()
        {
            string mid = ", middle part,";

            // Anonymous Method
            DelegateTest anonDel = delegate(string param)
            {
                param += mid;
                param += " and this was added to the string.";
                return(param);
            };

            // Lambda Expression
            //DelegateTest anonDel = param =>
            //   {
            //      param += mid;
            //      param += " and this was added to the string.";
            //      return param;
            //   };

            Console.WriteLine(anonDel("Start of string"));
        }
Exemplo n.º 33
0
 public void Remove(DelegateTest isTarget)
 {
     for (int i = 0; i < Count(); ++i) {
         object[] data = listModel[i];
         if (isTarget(data)) {
             Remove(i);
             --i;
         }
     }
 }
Exemplo n.º 34
0
 private void button10_Click(object sender, EventArgs e)
 {
     DelegateTest test = new DelegateTest();
 }