C# new

在c#中,new是关键字之一,new关键字主要有以下两个用途:运算符、修饰符。

1、运算符(operator)

new运算符用于创建对象和调用构造函数。
有三种形式的new表达式:

  • 对象创建表达式用来创建类类型(class type)和值类型(value type)新的实例。
  • 数组创建表达式用来创建数组类型(array type)的新的实例。
  • 委托创建表达式用来创建委托类型(delegate type)的新的实例。

1.1 对象创建表达式

class Program
{
    static void Main(string[] args)
    {
        Student stu1 = new Student(15, "Mike");
        Console.WriteLine(stu1.Age);
        Console.WriteLine(stu1.Name);
    }
}

class Student
{
    private int age;

    public int Age
    {
        get { return age; }
        set { age = value; }
    }

    private string name;

    public string Name
    {
        get { return name; }
        set { name = value; }
    }

    public Student(int age, string name)
    {
        this.age = age;
        this.name = name;
    }
}
class Program
{
    static void Main(string[] args)
    {
        int a = new int();
        a = 10;
        //等价于
        //int a = 10;
        Console.WriteLine(a);
    }
}

1.2 数组创建表达式

class Program
{
    static void Main(string[] args)
    {
        int[] array = new int[] { 1, 2, 3, 4 };
        foreach (var i in array)
        {
            Console.WriteLine(i);
        }
    }
}

1.3 委托创建表达式

delegate int NumberProcess(int a,int b);

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            NumberProcess n = new NumberProcess(Add);
            Console.WriteLine(n(2, 3));
        }

        static int Add(int a,int b)
        {
            return a + b;
        }
    }
}

2、修饰符(modifier)

用作声明修饰符时,new 关键字可以显式隐藏从基类继承的成员。

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Teather t = new Teather();
            Console.WriteLine(t.age);
            Console.WriteLine(t.name);
        }
    }

    class Person
    {
        public int age = 10;
        public string name = "Mike";
    }

    class Teather:Person
    {
        new public int age = 15;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值