How to: Use the Namespace Alias Qualifier 


Мы поможем в написании ваших работ!



ЗНАЕТЕ ЛИ ВЫ?

How to: Use the Namespace Alias Qualifier



The ability to access a member in the global namespace is useful when the member might be hidden by another entity of the same name.

For example, in the following code, Console resolves to TestApp.Console instead of to the Console type in the System namespace.

using System;
class TestApp { // Define a new class called 'System' to cause problems. public class System { } // Define a constant called 'Console' to cause more problems. const int Console = 7; const int number = 66; static void Main() { // Error Accesses TestApp.Console //Console.WriteLine(number); } }

Using System.Console still results in an error because the System namespace is hidden by the class TestApp.System:

// Error Accesses TestApp.System System.Console.WriteLine(number);

However, you can work around this error by using global::System.Console, like this:

// OK global::System.Console.WriteLine(number);

When the left identifier is global, the search for the right identifier starts at the global namespace. For example, the following declaration is referencing TestApp as a member of the global space.

class TestClass: global::TestApp

Obviously, creating your own namespaces called System is not recommended, and it is unlikely you will encounter any code in which this has happened. However, in larger projects, it is a very real possibility that namespace duplication may occur in one form or another. In these situations, the global namespace qualifier is your guarantee that you can specify the root namespace.


Использование квалификатора псевдонима пространства имен

Возможность доступа к члену в глобальном пространстве имен полезна, когда этот член может быть скрыт другой сущностью с таким же именем.

Например, в следующем коде Console разрешается в тип TestApp.Console вместо типа Console в пространстве имен System.

ß---

При использовании System.Console все равно возникает ошибка, так как пространство имен System скрыто классом TestApp.System:

// Error Accesses TestApp.System System.Console.WriteLine(number);

Однако данную ошибку можно устранить следующим образом, используя global::System.Console:

// OK global::System.Console.WriteLine(number);

Когда левый идентификатор имеет значение global, поиск правого идентификатора начинается в глобальном пространстве имен. Например, следующее объявление ссылается на TestApp как на член глобального пространства.

class TestClass: global::TestApp

Очевидно, что необходимость в создании пространства имен System отсутствует, а вероятность повстречать код, где это сделано, очень мала. Однако в более крупных проектах существует большая вероятность встретить ту или иную форму дублирования пространства имен. В такой ситуации квалификатор глобального пространства имен является гарантирует возможность задания корневого пространства имен.

 


Example

In this example, the namespace System is used to include the class TestClass therefore, global::System.Console must be used to reference the System.Console class, which is hidden by the System namespace. Also, the alias colAlias is used to refer to the namespace System.Collections; therefore, the instance of a System.Collections..::.Hashtable was created using this alias instead of the namespace.

using colAlias = System.Collections; namespace System { class TestClass { static void Main() { // Searching the alias: colAlias::Hashtable test = new colAlias::Hashtable();   // Add items to the table. test.Add("A", "1"); test.Add("B", "2"); test.Add("C", "3");   foreach (string name in test.Keys) { // Seaching the gloabal namespace: global::System.Console.WriteLine(name + " " + test[name]); } } } }
A 1 B 2 C 3

 


Пример

В данном примере пространство имен System используется для включения класса TestClass, поэтому для создания ссылки на класс System.Console, скрытый пространством имен System, необходимо использовать global::System.Console. Кроме того, псевдоним colAlias используется для создания ссылки на пространство имен System.Collections; таким образом при создании экземпляра System.Collections..::.Hashtable вместо пространства имен использовался этот псевдоним.

ß----


Nullable Types

Nullable types are instances of the System..::.Nullable<(Of <(T>)>) struct. A nullable type can represent the correct range of values for its underlying value type, plus an additional null value. For example, a Nullable<Int32>, pronounced "Nullable of Int32," can be assigned any value from -2147483648 to 2147483647, or it can be assigned the null value. A Nullable<bool> can be assigned the values truefalse, or null. The ability to assign null to numeric and Boolean types is especially useful when you are dealing with databases and other data types that contain elements that may not be assigned a value. For example, a Boolean field in a database can store the values true or false, or it may be undefined.

class NullableExample { static void Main() { int? num = null; if (num.HasValue == true) { System.Console.WriteLine("num = " + num.Value); } else { System.Console.WriteLine("num = Null"); }   //y is set to zero int y = num.GetValueOrDefault();   // num.Value throws an InvalidOperationException if num.HasValue is false try { y = num.Value; } catch (System.InvalidOperationException e) { System.Console.WriteLine(e.Message); } } }

The example will display the output:

num = Null

Nullable object must have a value.

 



Поделиться:


Последнее изменение этой страницы: 2017-01-19; просмотров: 106; Нарушение авторского права страницы; Мы поможем в написании вашей работы!

infopedia.su Все материалы представленные на сайте исключительно с целью ознакомления читателями и не преследуют коммерческих целей или нарушение авторских прав. Обратная связь - 18.191.181.231 (0.007 с.)