Форум программистов, компьютерный форум, киберфорум
C# для начинающих
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.75/4: Рейтинг темы: голосов - 4, средняя оценка - 4.75
3 / 3 / 3
Регистрация: 29.02.2016
Сообщений: 175
1

Как создать объект делегата и вызвать его?

13.10.2016, 12:47. Показов 815. Ответов 2
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Добрый день! Написал код, нужно: создать объект делегата и вызвать его
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
 
namespace WindowsFormsApplication66
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
 
        delegate int A(int a);
        delegate string B(string b); // создал делегаты
    
 
        public static string nat(string n)
        {
            return n;
        }
 
        public static int age(int a)
        {
            return a;
        }
 
        public static string s(string sud)
        {
            return sud;
        }
 
        public static string obraz(string obr)
        {
            return obr;
        }
 
        public static int staj(int s)
        {
            return s;                  // Организуем методы 
        }
 
        
 
 
        public void meth()
        {
            int ball = 0;
            B op1 = new B(nat);            // Сконструируем делегат
            string names = op1(textBox1.Text);
            if (textBox1.Text == "русский")  // национальность 
            {
                ball += 1;
            }
            else
            { ball = 0; }
 
 
 
 
 
            string sud = op1(textBox2.Text);
 
            if (textBox2.Text == "да")
            {
                ball = 0;
            }
            else
            { ball += 1; }
 
 
 
            op1 = new B(obraz);           // Сконструируем делегат 
            string ob = op1(textBox5.Text);
            if (textBox5.Text == "высшее")
            {
                ball += 1;
            }
            if (textBox5.Text == "среднее")
            {
                ball += 1;
            }
            if (textBox5.Text == "нет")
            {
                ball += 0;
            }
 
 
            A op2 = new A(age);        //  Сконструируем делегат
            int op = op2(Convert.ToInt16(textBox3.Text));
            if (Convert.ToInt16(textBox3.Text) < 25)  // Возраст 
            {
                ball = 0;
 
            }
            else { ball += 1; }
 
 
 
 
            A op4 = new A(staj); // Сконструируем делегат
            op2(Convert.ToInt16(textBox6.Text));   // Стаж 
            if (Convert.ToInt16(textBox6.Text) < 4)
            {
                ball = 0;
 
            }
            else { ball += 1; }
 
 
 
 
 
            if (ball >3 )
            {
                textBox4.Text = "Вы приняты на работу количество ваших баллов ";
 
            }
            else { textBox4.Text = "Вы не приняты на работу количество ваших баллов "; }
       
 
        }
 
       
 
 
 
 
        private void button1_Click(object sender, EventArgs e)
        {
            meth();
        }
    }
}
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
13.10.2016, 12:47
Ответы с готовыми решениями:

Как создать метод и вызвать его
Всем привет. Вопрос заключается в следующем. Только начинаю изучать C# и столкнулся со следующей...

Вызвать объект по его свойству
Как сообщить это машине: если а = 1, то вызывается объектА, у которого объектА.поле1 = 1 если...

Как создать обработчик для button и правильно его вызвать?
aspx генерирует html с множеством кнопок, кнопки создаются через &lt;button&gt;&lt;/button&gt;. как можно...

Как создать указатель на функцию-член класса и вызвать его?
Подскажите как правильно сделать, а в дальнейшем вызвать указатель на функцию член класса:...

2
3 / 3 / 3
Регистрация: 29.02.2016
Сообщений: 175
13.10.2016, 12:48  [ТС] 2
Добрый день! Написал код, нужно: создать объект делегата и вызвать его, как это сделать нигде не нашел об этом информации
Миниатюры
Как создать объект делегата и вызвать его?  
0
1494 / 1209 / 821
Регистрация: 29.02.2016
Сообщений: 3,614
13.10.2016, 12:59 3
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace DelegateExample
{
    // Declaration
    public delegate void myDelegate(string s);
 
    class myClass
    {
        public void myMethod1(string s)
        {
            Console.WriteLine(s + " from instance method1\n");
        }
 
        public static void myMethod2(string s)
        {
            Console.WriteLine(s + " from static method2\n");
        }
    } 
 
    class Program
    {
        static void Main(string[] args)
        {
            //Example illustrating different ways to work with 
            //delegate objects
 
            //(1) Working with instance methods.
 
            //Instantiate a null delegate object called delObj1.
            myDelegate delObj1 = null; //Delegate Instantiation
 
            //Instantiate an object called myObj from myClass 
            //class.
            myClass myObj = new myClass();
 
            //Assign instance method myMethod1 to delegate 
            //object delObj1. 
            delObj1 = myObj.myMethod1;
 
            //Use the delegate object delObj1 to pass some data 
            //to myMethod1.
            delObj1("Hello");  //Invocation
 
            //(2) Working with static methods.
 
            //Instantiate a null delegate object called delObj2.
            myDelegate delObj2 = null; //Delegate Instantiation
 
            //Assign static method myMethod2 to delegate object 
            //delObj2. Note that because myMethod2 is a static  
            //method, there is no need to first instantiate an  
            //object from myClass in order to then assign 
            //myMethod2 to delegage object delObj2.
            delObj2 = myClass.myMethod2;
 
            //Use the delegate object delObj2 to pass some 
            //data to myMethod2
            delObj2("Greetings");  //Invocation              
 
            //(3) Working with instance and static methods to  
            //build an invocation list
 
            //Create two delegate objects and directly assign 
            //them to their respective instance and static methods.
 
            //Delegate instantiation 
            myDelegate delObj3 = new myDelegate(myObj.myMethod1);
            //and invocation
            delObj3("Building invocation list, element 1");
 
            //Delegate instantiation 
            myDelegate delObj4 = new myDelegate(myClass.myMethod2);
            //and invocation
            delObj4("Building invocation list, element 2");
 
            //Build an invocation list from these two 
            //delegate objects
            myDelegate delObjTotal = delObj3 + delObj4;
 
            //Process the invocation list with some data
            delObjTotal("Processing entire invocation list.");
 
            //Remove a method from invocation list
            delObjTotal -= delObj4;
 
            //Process remaining methods in invocation list
            delObjTotal("Last message is");
 
            //Alternate way to build invocation list
            myDelegate delObj5 = null;
            delObj5 += new myDelegate(myObj.myMethod1);
            delObj5 += new myDelegate(myClass.myMethod2);
 
            //Process total invocation list with some data
            delObj5("bye...");
 
            //Remove a method from invocation list
            delObj5 -= myClass.myMethod2;
 
            //Process remaining methods in invocation list
            delObj5("Final message is");
 
            //Pause until user hits enter key
            Console.ReadLine(); 
        }
    }
}
0
13.10.2016, 12:59
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
13.10.2016, 12:59
Помогаю со студенческими работами здесь

Как создать метод, чтобы его можно было бы вызвать из другого класса?
Как создать метод, чтобы его можно было бы вызвать из другого класса? Создаю в Form1.cs метод для...

Как создать объект по его типу, не используя конструктор?
Необходимо создать объект, зная его тип. Activator.CreateInstanc использует конструктор, так что он...

Вызвать 2 функции с помощью делегата
как вызвать эти 2 функций с помощью делегата using System; using System.Collections.Generic;...

Как в одну строку создать новый объект, и получить его свойство
Вот мой код: Class Db{ public $connection; function __construct($host, $db, $user, $pass){...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
3
Ответ Создать тему
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru