C# new用法总结-转

有一道这样的题:写出c#中new关键字的三种用法,思前想后挖空心思也只想出了两种用法,回来查了下msdn,还真是有第三种用法: 用于在泛型声明中约束可能用作类型参数的参数的类型,这是在Framework 2.0 中定义泛行时才会使用到的,自己对c# 2.0 中的支持还只是 粗通皮毛,怪不得累死so many脑细胞也没能想不出这第三种来! 

 
三种用法如下:
 C# 中,new 关键字可用作运算符、修饰符或约束。
1)new 运算符:用于创建对象和调用构造函数。这种大家都比较熟悉,没什么好说的了。
2)new 修饰符在用作修饰符时,new 关键字可以显式隐藏从基类继承的成员。
3)new 约束:用于在泛型声明中约束可能用作类型参数的参数的类型。 
 

关于第二种用法看下例

using System;
namespace ConsoleApplication1
{
    public class BaseA
    {
        public int x = 1;
        public void Invoke()
        {
            Console.WriteLine(x.ToString());
        }
        public int TrueValue
        {
            get { return x; }
            set { x = value; }
        }
    }
    public class DerivedB : BaseA
    {
        new public int x = 2;
        new public void Invoke()
        {
            Console.WriteLine(x.ToString());
        }
        new public int TrueValue
        {
            get { return x; }
            set { x = value; }
        }
    }
 
    class Test
    {
        static void Main(string[] args)
        {
            DerivedB b = new DerivedB();
            b.Invoke();//调用DerivedB的Invoke方法,输出:2
            Console.WriteLine(b.x.ToString());//输出DerivedB的成员x值:2
            BaseA a = b;
            a.Invoke();//调用BaseA的Invoke方法,输出:1
            a.TrueValue = 3;//调用BaseA的属性TrueValue,修改BaseA的成员x的值
            Console.WriteLine(a.x.ToString());//输出BaseA的成员x的值:3
            Console.WriteLine(b.TrueValue.ToString());//输出DerivedB的成员x的值,仍然是:1
//可见,要想访问被隐藏的基类的成员变量、属性或方法,办法就是将子类造型为父类,然
//后通过基类访问被隐藏的成员变量、属性或方法。
        }
     }
}
new约束指定泛型类声明中的任何类型参数都必须具有公共的无参数构造函数.请看下例:
 1 using System;
 2 using System.Collections.Generic;
 3  
 4 namespace ConsoleApplication2
 5 {
 6     public class Employee
 7     {
 8         private string name;
 9         private int id;
10  
11         public Employee()
12         {
13             name = "Temp";
14             id = 0;
15         }
16  
17         public Employee(string s, int i)
18         {
19             name = s;
20             id = i;
21         }
22  
23         public string Name
24         {
25             get { return name; }
26             set { name = value; }
27         }
28  
29         public int ID
30         {
31             get { return id; }
32             set { id = value; }
33         }
34     }
35  
36     class ItemFactory<T> where T : new()
37     {
38         public T GetNewItem()
39         {
40             return new T();
41         }
42     }
43  
44     public class Test
45     {
46         public static void Main()
47         {
48             ItemFactory<Employee> EmployeeFactory = new ItemFactory<Employee>();
49             ////此处编译器会检查Employee是否具有公有的无参构造函数。
50             //若没有则会有The Employee must have a public parameterless constructor 错误。
51             Console.WriteLine("{0}'ID is {1}.", EmployeeFactory.GetNewItem().Name, EmployeeFactory.GetNewItem().ID);
52         }
53     }
54 }