共计 859 个字符,预计需要花费 3 分钟才能阅读完成。
导读 | 这篇文章介绍了 C# 中 new 操作符的工作机制,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下 |
使用 new 操作符来创建对象,其背后到底发生了什么?
有一个父类 Animal,Dog 派生于 Animal。
class Program | |
{static void Main(string[] args) | |
{Dog dog = new Dog(); | |
Console.WriteLine("我能调用老祖宗 Object 的实例方法 GetType, 显示结果为:" + dog.GetType() ); | |
Console.WriteLine("我能拿到父类的属性 Age=" + dog.Age); | |
Console.WriteLine("我当然能拿到自己的公共字段_weight=" + dog._weight); | |
} | |
} | |
public class Animal | |
{public int Age { get; set;} | |
public Animal(){} | |
} | |
public class Dog : Animal | |
{ | |
public decimal _weight; | |
public Dog(){} | |
} |
虽然创建了子类 Dog 的实例,但通过 dog 实例能调用 ” 老祖宗 ”System.Object 的实例方法,也能获取到父类的公共属性 Age 的值,并且所有的实例字段值为其类型的默认值。
new 操作符做的事情大致包括:
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值
正文完
星哥玩云-微信公众号
