New 关键字

new关键字有如下几种用法:

1. 作为运算符

  1)Object obj= new Object();

   new 运算符不能重载,如果在初始化对象时失败,会抛出OutOfMemoryException 异常。

2. 作为修饰符

  使用 new 修饰符显式隐藏从基类继承的成员。若要隐藏继承的成员,请使用相同名称在派生类中声明该成员,并用 new 修饰符修饰它。

  Sample:

BASE CLASS:

    public class Base

    {

        private string str1;

        public string Str1

        {

            get

            {

                return str1;

            }

            set

            {

                str1 = value;

            }

        }

 

        public Base(string str1)

        {

            this.str1 = str1;

        }

 

        public string Method1()

        {

            return this.str1;

        }

    }

Inheriate Class:

 public class Inheritate:Base

    {

        private string str2;

        public string Str2

        {

            set { this.str2 = value; }

            get { return this.str2; }

        }

        public Inheritate(string str2, string str1)

            : base(str1)

        {

 

            this.str2 = str2;

        }

 

        public new string Method1()

        {

            return this.Str1 + "" + this.Str2;

        }

    }

New 不仅可以放在成员变量,成员函数上,也可以放在类上。

 

3. 用于泛型类型约束 new 约束

new 约束指定泛型类声明中的任何类型参数都必须有公共的无参数构造函数。 如果要使用 new 约束,则该类型不能为抽象类型。

    class ItemFactory<T> where T : new()
    {
        public T GetNewItem()
        {
            return new T();
        }
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值