How to: Call a Method on an Object
This example calls an instance method, myMethod, referenced through an instance of the class.
Example
class Program { static void Main(string[] args) { Program myObject = new Program(); myObject.myMethod(); } void myMethod() { // Do something } } |
Compiling the Code
Copy the code, and paste it into a console application and build the solution.
Robust Programming
Use the fully qualified name of the method, unless it is accessible from the same scope.
If the method is static, you should not reference it through an instance of the class.
When assigning an expression to a property, make sure of the following:
· That it is of a compatible data type.
· That it has a valid value, especially if the value is derived from user input.
Вызов метода в объекте
В этом примере создается экземпляр myObject класса Program и этот экземпляр вызывает метод myMethod класса Program
Пример
class Program { static void Main(string[] args) { Program myObject = new Program(); myObject.myMethod(); } void myMethod() { // Do something } } |
Компиляция кода
Скопируйте код, вставьте его в консольное приложение и постройте решение.
How to: Inherit From a Class
This example defines the Circle and Rectangle classes, which both inherit from the Shape class, and the Square class, which inherits from the Rectangle class.
Example
public class Shape { // Definitions of properties, methods, fields, and events. } public class Circle : Shape { // Specialized properties, methods, fields, events for Circle. } public class Rectangle : Shape { // Specialized properties, methods, fields, events for Rectangle. } public class Square : Rectangle { // Specialized properties, methods, fields, events for Square. } |
Compiling the Code
· Start a new console application.
· Copy the code and paste it right before or after Class1 declaration.
Robust Programming
Make sure the class you want to inherit is not sealed.
Наследование от класса
В этом примере определяются классы Circle и Rectangle, которые оба наследуют от класса Shape, и класс Square, наследуемый от класса Rectangle.
Пример
public class Shape { // Definitions of properties, methods, fields, and events. } public class Circle : Shape { // Specialized properties, methods, fields, events for Circle. } public class Rectangle : Shape { // Specialized properties, methods, fields, events for Rectangle. } public class Square : Rectangle { // Specialized properties, methods, fields, events for Square. } |
Компиляция кода
· Запустите новое консольное приложение.
· Скопируйте и вставьте код до или после объявления Class1.[39]
Дата добавления: 2022-05-27; просмотров: 135;