C# 2.0 新特性

来源:互联网 发布:淘宝刷真实流量软件 编辑:程序博客网 时间:2024/06/11 12:26
C# 2.0 新特性:

1、泛型
List<MyObject> obj_list=new List();
obj_list.Add(new MyObject());

2、部分类(partial)
namespace xxx
{
public partial class Class1
{
private string _s1;
public string S1
{
get { return _s1; }
set { _s1 = value; }
}
}

//或在另一个文件中
public partial class Class1
{
public string GetString()
{
string s = this.S1 + "aaa";
return s;
}
}
}

3、静态类
public static class MyStaticObject
{
private static string _s;
static MyStaticObject()
{
_s = "Hello";
}
public static string Mothed1()
{
return _s + ",world.";
}
}

4、属性访问器可访问性
public class Class2
{
private string _str;
public string Str
{
get { return _str; }
protected set { _str = value; }
}
}

5、可空类型
int? aa = null;
aa = 23;
if (aa.HasValue)
{
int bb = aa.Value;
}

6、匿名方法
class SomeClass //在C#1.0中
{
delegate void SomeDelegate();
public void InvokeMethod()
{
SomeDelegate del = new SomeDelegate(SomeMethod);
del();
}
void SomeMethod()
{
MessageBox.Show("Hello");
}
}

class SomeClass2
{
public delegate void SomeDelegate();
public void InvokeMothed()
{
SomeDelegate del = delegate {
MessageBox.Show("Hello");
};
del();
}
}

7、名称空间别名限定符

global::

转载自http://blog.sina.com.cn/s/blog_5387d4f20100jvi7.html

使用命名空间别名限定符

当成员可能被同名的其他实体隐藏时,能够访问全局命名空间中的成员非常有用。

例如,在下面的代码中,Console 在 System 命名空间中解析为 TestApp.Console 而不是 Console 类型。

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.SystemSystem.Console.WriteLine(number);

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

// OKglobal::System.Console.WriteLine(number);

当左侧的标识符为 global 时,对右侧标识符的搜索将从全局命名空间开始。例如,下面的声明将 TestApp 作为全局空间的一个成员进行引用。

class TestClass : global::TestApp

显然,并不推荐创建自己的名为 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 1B 2C 3
转自MSDN:http://msdn.microsoft.com/zh-cn/library/c3ay4x3d(VS.80).aspx

原创粉丝点击