Студопедия

КАТЕГОРИИ:


Архитектура-(3434)Астрономия-(809)Биология-(7483)Биотехнологии-(1457)Военное дело-(14632)Высокие технологии-(1363)География-(913)Геология-(1438)Государство-(451)Демография-(1065)Дом-(47672)Журналистика и СМИ-(912)Изобретательство-(14524)Иностранные языки-(4268)Информатика-(17799)Искусство-(1338)История-(13644)Компьютеры-(11121)Косметика-(55)Кулинария-(373)Культура-(8427)Лингвистика-(374)Литература-(1642)Маркетинг-(23702)Математика-(16968)Машиностроение-(1700)Медицина-(12668)Менеджмент-(24684)Механика-(15423)Науковедение-(506)Образование-(11852)Охрана труда-(3308)Педагогика-(5571)Полиграфия-(1312)Политика-(7869)Право-(5454)Приборостроение-(1369)Программирование-(2801)Производство-(97182)Промышленность-(8706)Психология-(18388)Религия-(3217)Связь-(10668)Сельское хозяйство-(299)Социология-(6455)Спорт-(42831)Строительство-(4793)Торговля-(5050)Транспорт-(2929)Туризм-(1568)Физика-(3942)Философия-(17015)Финансы-(26596)Химия-(22929)Экология-(12095)Экономика-(9961)Электроника-(8441)Электротехника-(4623)Энергетика-(12629)Юриспруденция-(1492)Ядерная техника-(1748)

Example. Вызов метода в объекте




Компиляция кода

Пример

Robust Programming

Compiling the Code

Example

Компиляция кода

Пример

Вызов метода в объекте

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.

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. }

· Start a new console application.

· Copy the code and paste it right before or after Class1 declaration.

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]


How to: Simulate Default Parameters

This example demonstrates the use of method overloading to simulate default parameters, which is not allowed in C#.

class MyClass

{

static string myMethod(string precip, string country, string location)

{

return string.Format("The {0} in {1} stays mainly in the {2}.",

precip, country, location);

}

static string myMethod(string precip, string country)

{

return myMethod(precip, country, "plain");

}

static string myMethod()

{

return myMethod("rain", "Spain", "plain");

}

static void Main(string[] args)

{

System.Console.WriteLine(myMethod());

System.Console.WriteLine(myMethod("snow", "Walla Walla"));

}

}




Поделиться с друзьями:


Дата добавления: 2014-12-27; Просмотров: 393; Нарушение авторских прав?; Мы поможем в написании вашей работы!


Нам важно ваше мнение! Был ли полезен опубликованный материал? Да | Нет



studopedia.su - Студопедия (2013 - 2024) год. Все материалы представленные на сайте исключительно с целью ознакомления читателями и не преследуют коммерческих целей или нарушение авторских прав! Последнее добавление




Генерация страницы за: 0.009 сек.