关于new的一道面试题-写出new关键字的三种用法

关于new的一道面试题-写出new关键字的三种用法:

  一次面试中面试员问在C#中关于new关键字使用的三种方法,当时只回答了一种,面试结束后查询了一下有三种方法(参照MSDN)。下面把这三种方法介绍下:

  1.new 运算符:用于创建对象和调用构造函数;(我的回答)

  2.new修饰符:用于隐藏积累中被继承的成员;

  3.new约   束:用于在泛型声明中约束可能用作类型参数的类型。

详细介绍:

  第一种用法示例

  通过使用 new 运算符创建并初始化一个 struct 对象和一个类对象,然后为它们赋值。 显示了默认值和所赋的值。

 1 struct SampleStruct
 2 {
 3    public int x;
 4    public int y;
 5 
 6    public SampleStruct(int x, int y)
 7    {
 8       this.x = x;
 9       this.y = y;
10    }
11 }
12 
13 class SampleClass
14 {
15    public string name;
16    public int id;
17 
18    public SampleClass() {}
19 
20    public SampleClass(int id, string name)
21    {
22       this.id = id;
23       this.name = name;
24    }
25 }
26 
27 class ProgramClass
28 {
29    static void Main()
30    {
31       // Create objects using default constructors:
32       SampleStruct Location1 = new SampleStruct();
33       SampleClass Employee1 = new SampleClass();
34 
35       // Display values:
36       Console.WriteLine("Default values:");
37       Console.WriteLine("   Struct members: {0}, {1}",
38              Location1.x, Location1.y);
39       Console.WriteLine("   Class members: {0}, {1}",
40              Employee1.name, Employee1.id);
41 
42       // Create objects using parameterized constructors:
43       SampleStruct Location2 = new SampleStruct(10, 20);
44       SampleClass Employee2 = new SampleClass(1234, "Cristina Potra");
45 
46       // Display values:
47       Console.WriteLine("Assigned values:");
48       Console.WriteLine("   Struct members: {0}, {1}",
49              Location2.x, Location2.y);
50       Console.WriteLine("   Class members: {0}, {1}",
51              Employee2.name, Employee2.id);
52    }
53 }
54 /*
55 Output:
56 Default values:
57    Struct members: 0, 0
58    Class members: , 0
59 Assigned values:
60    Struct members: 10, 20
61    Class members: Cristina Potra, 1234
62 */
View Code

  第二中用法示例

  基类 BaseC 和派生类 DerivedC 使用相同的字段名 x,从而隐藏了继承字段的值。 此示例演示 new 修饰符的用法。 另外还演示了如何使用完全限定名访问基类的隐藏成员。

 1 public class BaseC
 2 {
 3     public static int x = 55;
 4     public static int y = 22;
 5 }
 6 
 7 public class DerivedC : BaseC
 8 {
 9     // Hide field 'x'.
10     new public static int x = 100;
11 
12     static void Main()
13     {
14         // Display the new value of x:
15         Console.WriteLine(x);
16 
17         // Display the hidden value of x:
18         Console.WriteLine(BaseC.x);
19 
20         // Display the unhidden member y:
21         Console.WriteLine(y);
22     }
23 }
24 /*
25 Output:
26 100
27 55
28 22
29 */
View Code

  第二中用法示例

  当泛型类创建类型的新实例,请将 new 约束应用于类型参数,如下面的示例所示:

 1  class ItemFactory<T> where T : new()
 2     {
 3         public T GetNewItem()
 4         {
 5             return new T();
 6         }
 7     }
 8 
 9     当与其他约束一起使用时,new() 约束必须最后指定:
10   public class ItemFactory2<T>
11         where T : IComparable, new()
12     {
13     }
View Code
Top
收藏
关注
评论
原文地址:https://www.cnblogs.com/fei12/p/3786355.html