How to: Set a Property on an Object


This example sets the CurrentDirectory property on the Environment class to C:\Public.

Example

Environment.CurrentDirectory = "C:\\Public";

-or-

Environment.CurrentDirectory = @"C:\Public";

Compiling the Code

Copy the code, and paste it into the Main method of a console application.

Robust Programming

Use the fully qualified name of the property, unless it is accessible from the same scope.

Unless the property is static, it must be referenced 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.

If you want more control over possible exceptions, enclose the property assignment in a try-catch statement.


Задание свойства объекта

В этом примере свойству CurrentDirectory в классе Environment задается значение C:\Public.

Пример

Environment.CurrentDirectory = "C:\\Public";

или

Environment.CurrentDirectory = @"C:\Public";

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

Скопируйте код и вставьте его в метод Main консольного приложения.


Structs

A struct in C# is similar to a class, but structs lack certain features, such as inheritance. Also, since a struct is a value type, it can typically be created faster than a class. If you have tight loops in which new data structures are being created in large numbers, you should consider using a struct instead of a class. Structs are also used to encapsulate groups of data fields such as the coordinates of a point on a grid, or the dimensions of a rectangle.

Example

This example program defines a struct to store a geographic location. It also overrides the ToString() method to produce a more useful output when displayed in the WriteLine statement. As there are no methods in the struct, there is no advantage in defining it as a class.

struct GeographicLocation { private double longitude; private double latitude;   public GeographicLocation(double longitude, double latitude) { this.longitude = longitude; this.latitude = latitude; } public override string ToString() { return System.String.Format("Longitude: {0} degrees, Latitude: {1} degrees", longitude, latitude); } } class Program { static void Main() { GeographicLocation Seattle = new GeographicLocation(123, 47); System.Console.WriteLine("Position: {0}", Seattle.ToString()); } }

Output

The output from this example looks like this:

Position: Longitude: 123 degrees, Latitude: 47 degrees


Структуры

Структура в C# аналогична классу, однако в структурах отсутствуют некоторые возможности, например наследование. Кроме того, поскольку структура является типом значения, ее можно создать быстрее, чем класс. При наличии непрерывного цикла, где создается большое количество новых структур данных, вместо класса рекомендуется использовать структуру. Структуры используются для инкапсуляции групп полей данных, таких как координаты точки в сетке или размеры прямоугольника.

Пример

В следующем примере программы определяется struct для сохранения географического расположения. Здесь также переопределяется метод ToString() для вывода более необходимых результатов при отображении в операторе WriteLine. Поскольку в struct методы отсутствуют, определение структуры в качестве класса бессмысленно.[42]

ß-----

 

 

Результат

После выполнения примера выводится следующий результат.

Position: Longitude: 123 degrees, Latitude: 47 degrees


 



Дата добавления: 2022-05-27; просмотров: 126;


Поиск по сайту:

Воспользовавшись поиском можно найти нужную информацию на сайте.

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

Считаете данную информацию полезной, тогда расскажите друзьям в соц. сетях.
Poznayka.org - Познайка.Орг - 2016-2024 год. Материал предоставляется для ознакомительных и учебных целей.
Генерация страницы за: 0.007 сек.