How to: Simulate Default Parameters
This example demonstrates the use of method overloading to simulate default parameters, which is not allowed in C#.
Example
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"));
}
}
Compiling the Code
Copy the class and paste it over Class1 in a console application.
Имитация параметров по умолчанию
В этом примере демонстрируется использование перегрузки метода для имитации параметров по умолчанию.
Пример
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")); } } |
Компиляция кода
Скопируйте класс и вставьте его поверх Class1 в консольном приложении.[40]
How to: Declare a Property
This example declares an instance property.
Example
private string name;
// A read-write instance property:
public string NameProperty
{
get
{
return name;
}
set
{
name = value;
}
}
Compiling the Code
The code must appear within a class or a struct.
Robust Programming
· You can use the get accessor to either return the field value or compute the value and return it, as follows:
get { return (name != null) ? name : "NA"; } |
Do not use the get accessor to change the state of the object, as follows: get { return myNumericField++; } |
Объявление свойства
В этом примере объявляется свойство экземпляра.
Пример
ß---------
Компиляция кода
Код должен появиться в классе или структуре.
Надежное программирование
· Метод доступа get можно использовать для возвращения значения поля или для вычисления и возвращения этого значения, как показано в следующем примере.
get { return (name != null) ? name : "NA"; } |
Для изменения состояния объекта метод доступа get использовать нельзя.[41] get { return myNumericField++; } |
Дата добавления: 2022-05-27; просмотров: 154;