C windows form return

Оператор return (C) return Statement (C)

Оператор return завершает выполнение функции и возвращает управление вызывающей функции. A return statement ends the execution of a function, and returns control to the calling function. Выполнение возобновляется в вызывающей функции в точке сразу после вызова. Execution resumes in the calling function at the point immediately following the call. Оператор return может возвращать значение, передавая его вызывающей функции. A return statement can return a value to the calling function. Дополнительные сведения см. в статье Тип возвращаемого значения. For more information, see Return type.

Синтаксис Syntax

оператор_перехода: jump-statement:
return выражение(необязательно) ; return expressionopt ;

Значение параметра выражение, если оно указано, возвращается вызывающей функции. The value of expression, if present, is returned to the calling function. Если параметр выражение опущен, возвращаемое значение функции не определено. If expression is omitted, the return value of the function is undefined. Параметр «выражение», если он присутствует, вычисляется и преобразуется к типу, возвращаемому функцией. The expression, if present, is evaluated and then converted to the type returned by the function. Если оператор return содержит выражение в функциях, имеющих тип возвращаемого значения void , то компилятор выдает предупреждение, а выражение не вычисляется. When a return statement contains an expression in functions that have a void return type, the compiler generates a warning, and the expression isn’t evaluated.

Если в определении функции оператор return не указан, то после выполнения последнего оператора вызванной функции управление автоматически возвращается вызывающей функции. If no return statement appears in a function definition, control automatically returns to the calling function after the last statement of the called function is executed. В этом случае возвращаемое значение вызванной функции не определено. In this case, the return value of the called function is undefined. Если функция имеет тип возвращаемого значения, отличный от void , это считается серьезной ошибкой и компилятор выводит предупреждающее диагностическое сообщение. If the function has a return type other than void , it’s a serious bug, and the compiler prints a warning diagnostic message. Если функция имеет тип возвращаемого значения void , то такое поведение приемлемо, но может считаться плохим стилем. If the function has a void return type, this behavior is okay, but may be considered poor style. Чтобы ваше намерение было понятным, используйте простой оператор return . Use a plain return statement to make your intent clear.

В качестве лучшей методики разработки рекомендуется всегда указывать тип возвращаемого значения для ваших функций. As a good engineering practice, always specify a return type for your functions. Если возвращаемое значение не требуется, объявите функцию как имеющую тип возвращаемого значения void . If a return value isn’t required, declare the function to have void return type. Если тип возвращаемого значения не указан, компилятор C предполагает, что по умолчанию используется тип возвращаемого значения int . If a return type isn’t specified, the C compiler assumes a default return type of int .

Читайте также:  Windows 10 не обновляется видеодрайвер

Многие программисты заключают аргумент выражения в операторе return в скобки. Many programmers use parentheses to enclose the expression argument of the return statement. Однако использовать эти скобки в языке C необязательно. However, C doesn’t require the parentheses.

Если компилятор обнаруживает операторы, размещенные после return , он может вывести предупреждающее диагностическое сообщение о недоступном для выполнения коде. The compiler may issue a warning diagnostic message about unreachable code if it finds any statements placed after the return statement.

В функции main оператор return и выражение являются необязательными. In a main function, the return statement and expression are optional. То, что происходит с указанным возвращаемым значением, зависит от реализации. What happens to the returned value, if one is specified, depends on the implementation. Только для систем Майкрософт: реализация C от Майкрософт возвращает значение выражения процессу, вызвавшему программу, например cmd.exe . Microsoft-specific: The Microsoft C implementation returns the expression value to the process that invoked the program, such as cmd.exe . Если выражение return не указано, среда выполнения C от Майкрософт возвращает значение, соответствующее успешному (0) или неудачному (ненулевое значение) выполнению. If no return expression is supplied, the Microsoft C runtime returns a value that indicates success (0) or failure (a non-zero value).

Пример Example

В этом примере показана одна программа из нескольких частей. This example is one program in several parts. Она демонстрирует оператор return и использование его для завершения выполнения функции и, при необходимости, возврата какого-то значения. It demonstrates the return statement, and how it’s used both to end function execution, and optionally, to return a value.

Функция square возвращает квадрат своего аргумента, используя более широкий тип для избежания арифметической ошибки. The square function returns the square of its argument, in a wider type to prevent an arithmetic error. Только для систем Майкрософт: в реализации C от Майкрософт тип long long достаточно велик, чтобы вмещать произведение двух значений int без переполнения. Microsoft-specific: In the Microsoft C implementation, the long long type is large enough to hold the product of two int values without overflow.

Скобки вокруг выражения return в функции square вычисляются как часть выражения, и использовать их в операторе return не требуется. The parentheses around the return expression in square are evaluated as part of the expression, and aren’t required by the return statement.

Читайте также:  Это устройство работает неправильно код 31 windows 10 видеокарта

Функция ratio возвращает частное двух int аргументов в виде значения double с плавающей запятой. The ratio function returns the ratio of its two int arguments as a floating-point double value. Выражение return принудительно использует операцию с плавающей запятой путем приведения одного из операндов к типу double . The return expression is forced to use a floating-point operation by casting one of the operands to double . В противном случае будет использоваться оператор целочисленного деления, а дробная часть будет потеряна. Otherwise, the integer division operator would be used, and the fractional part would be lost.

Функция report_square вызывает square со значением параметра INT_MAX — самым большим целым числом со знаком, которое помещается в int . The report_square function calls square with a parameter value of INT_MAX , the largest signed integer value that fits in an int . Результат типа long long сохраняется в squared , а затем выдается в выводе. The long long result is stored in squared , then printed. Функция report_square имеет тип возвращаемого значения void , поэтому она не содержит выражения в операторе return . The report_square function has a void return type, so it doesn’t have an expression in its return statement.

Функция report_ratio вызывает ratio со значениями параметров 1 и INT_MAX . The report_ratio function calls ratio with parameter values of 1 and INT_MAX . Результат типа double сохраняется в fraction , а затем выдается в выводе. The double result is stored in fraction , then printed. Функция report_ratio имеет тип возвращаемого значения void , поэтому явно возвращать значение не требуется. The report_ratio function has a void return type, so it doesn’t need to explicitly return a value. Выполнение report_ratio не дает результата и не возвращает вызывающей функции никакого значения. Execution of report_ratio «falls off the bottom» and returns no value to the caller.

Функция main вызывает две функции: report_square и report_ratio . The main function calls two functions: report_square and report_ratio . Поскольку report_square не принимает параметров и возвращает void , результат не присваивается переменной. As report_square takes no parameters and returns void , we don’t assign its result to a variable. Аналогичным образом функция report_ratio возвращает void , поэтому ее возвращаемое значение тоже не сохраняется. Likewise, report_ratio returns void , so we don’t save its return value, either. После вызова каждой из этих функций выполнение продолжается в следующем операторе. After each of these function calls, execution continues at the next statement. Затем main возвращает значение 0 (обычно свидетельствующее об успешном выполнении), чтобы завершить программу. Then main returns a value of 0 (typically used to report success) to end the program.

Читайте также:  Установка windows диск не инициализирован

C windows form return

This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.

Answered by:

Question

Answers

MyCustomForm oForm = new MyCustomForm();
oForm.ShowDialog(); // form is shown, do the actions in the form.
string a = oForm.MyProperty; // retrieve the public property from the form

in the code of your MyCustomForm you add this.

private string m_myProperty;

public string MyProperty
<
get
<
return this.m_myProperty;
>
>

In MyCustomForm you should work with the private member m_myProperty, and to get the property after the form is showed, you call the public member MyProperty.

All replies

can you just explain your question??

You could have a public property to give you access to a private field in the class that holds the return value.

Then you’d check the return value from ShowDialog() to see if the user cancelled or accepted, and if they accepted, you’d use the public property.

MyCustomForm oForm = new MyCustomForm();
oForm.ShowDialog(); // form is shown, do the actions in the form.
string a = oForm.MyProperty; // retrieve the public property from the form

in the code of your MyCustomForm you add this.

private string m_myProperty;

public string MyProperty
<
get
<
return this.m_myProperty;
>
>

In MyCustomForm you should work with the private member m_myProperty, and to get the property after the form is showed, you call the public member MyProperty.

Why don’t you just set the value directly like —

Form1.Label1.Text = Me.TextBox1.Text

Regards
Kapalic

This is bad programming.

A good program has its logical part and interface seperated. Now you acces the GUI from a logical part in the main form.
Use public properties or methods to set the GUI. If you want to change the GUI of the child form, then you don’t need to change the code in the main form. For example, when you want to change a label into a textbox, you can have more work with your way of programming.

This is a good way to do it (so far as I know).

Code in the main form where you create the child form:

MyForm oForm = new MyForm();
oForm.setUserName(«John»);
oForm.ShowDialog();

Code in the child form, the public method to set the GUI

public void setUserName(string name)
<
this.lblUserName = name; // label
>

and if you now change the label into a textbox control on the child form.

. yo u only have to change 1 line in the GUI/child form and nothing in the main form. If you create the form multiple times, you will understand why to do it this way.

Оцените статью