C# new 和 override的一些认知

来源:互联网 发布:c 编写windows程序 编辑:程序博客网 时间:2024/05/16 08:57

一、在 C# 中,new 关键字可用作运算符、修饰符或约束。


①、new 运算符

用于创建对象和调用构造函数。

eg:
class SampleClass{  
   public string name;   public int id;   public SampleClass() {}
   //构造函数重载
   public SampleClass(int id, string name)   {      this.id = id;      this.name = name;   }}
class ProgramClass{   static void Main()   {
      //创建对象和调用构造函数。
      SampleClass Employee1 = new SampleClass();
      SampleClass Employee2 = new SampleClass(1234, "Cristina Potra");      //do something using Employee1 and Employee2        }}


②、new 修饰符

用于隐藏基类中被继承的成员。

eg:
public class BaseC{    public static int x = 55;    public static int y = 22;}public class DerivedC : BaseC{    // Hide field 'x'.    new public static int x = 100;    static void Main()    {        // Display the new value of x:        Console.WriteLine(x);        // Display the hidden value of x:        Console.WriteLine(BaseC.x);        // Display the unhidden member y:        Console.WriteLine(y);    }}

③、new 约束

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

当泛型类创建类型的新实例,请将 new 约束应用于类型参数,如下面的示例所示:    
       class ItemFactory<T> where T : new()    {        public T GetNewItem()        {            return new T();        }    }


二、Override:

要扩展或修改继承的方法、属性、索引器或事件的抽象实现或虚实现,必须使用 override 修饰符。

Override的这个功能和new 作为修饰符的功能相似:Override是重写基类方法,new修饰符是隐藏基类中的方法或成员。

但是,要注意:

不能重写非虚方法或静态方法。 重写的基方法必须是 virtualabstract 或 override 的。

override 声明不能更改 virtual 方法的可访问性。 override 方法和 virtual 方法必须具有相同的访问级别修饰符。

您不能使用 newstatic 或 virtual 修饰符来修改 override 方法。

重写属性声明必须指定与继承属性完全相同的访问修饰符、类型和名称,并且被重写的属性必须是 virtualabstract 或 override 的。



0 0
原创粉丝点击