您的位置:首页 > 其它

可空修饰符/空合并运算符/命名空间别名限定符

2010-10-07 16:54 260 查看
1)可空类型修饰符“T?” :

可空类型的基础类型可以是任何非可空值类型或任何具有struct 约束的类型参数,但不能是可空类型或引用类型。例如:int? 代表是可空的整形,而int?? 则是无效类型。即可空类型可以表示其基础类型的所有值和一个额外的空值。语法T? 是System.Nullable 的缩写形式。可空类型具有一个HasValue 的bool 类型只读属性,当可空类型实例的该属性为true 时,则表示该实例是非空实例,包含一个已知值Value;HasValue 为false 时,访问Value 属性将导致System.InvalidOperationException 。可空类型T? 具有一个类型为T 的单个参数的公共构造函数,如new int?(123) 将获得一个值为123 的int? 类型实例。从T? 到由T 实现的任何接口都存在装箱转换,并且从由T 实现的任何接口都存在到T? 的拆箱转换。但是任何情况下可空类型都不满足接口约束,即使基础类型实现了该特定接口。

2)空合并运算符“??” :

该运算符是在泛型出现后,C# 词法语法中新增加的标记,同时出现的还有一个“::” (命名空间别名限定符)。形式为“a??b” 的空合并表达式要求a 为可空类型或引用类型 。如果a 为非空则表达式“a??b” 返回的结果为a ;否则返回b 。空合并运算符为 右 结合运算符 ,即操作时从右向左进行组合的。如,“a??b??c” 的形式按“a??(bb??cc)” 计算。

3)命名空间限定运算符::

C# global::命名空间别名限定符

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);
}
}


由于类 TestApp.System 隐藏了 System 命名空间,因此使用 System.Console 仍然会导致错误:

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

但是,可以通过使用 global::System.Console 避免这一错误,如下所示:

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

显然,并不推荐创建自己的名为 System 的命名空间,您不可能遇到出现此情况的任何代码。但是,在较大的项目中,很有可能在一个窗体或其他窗体中出现命名空间重复。在这种情况下,全局命名空间限定符可保证您可以指定根命名空间。

在此示例中,命名空间 System 用于包括类 TestClass,因此必须使用 global::System.Console 来引用 System.Console 类,该类被 System 命名空间隐藏。而且,别名 colAlias 用于引用命名空间 System.Collections;因此,将使用此别名而不是命名空间来创建 System.Collections.Hashtable 的实例。

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: