c new java_.NET(C#)new关键字的三种用法

1、new 运算符:用于创建对象和调用构造函数。这个我们创建对象实例就比较常用了,比如:StringBuilder str=new StringBuilder();

2、new 修饰符:在用作修饰符时,new 关键字可以显式隐藏从基类继承的成员。简单的说,就是现在写的这个类,想写一个和基类中相同的成员,而不继承基类的。运用多态的特性时,也不会调用这个显示隐藏的方法。具体看下如下代码:using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace ConsoleApp2

{

public class Program

{

static void Main(string[] args)

{

animal a = new animal();

a.name = "animal";

a.say();

cat c = new cat();

c.name = "cat";

c.say();

dog d = new dog();

d.name = "dog";

d.say();

sheep s = new sheep();

s.name = "sheep";

s.say();

animal a1 = new cat();

a1.say();

animal a2 = new dog();

a2.say();

animal a3 = new sheep();

a3.say();

}

}

class animal

{

public string name { get; set; }

public virtual void say()

{

Console.WriteLine("animal say");

}

}

class cat : animal

{

public override void say()

{

Console.WriteLine("cat say");

}

}

class dog : animal

{

public new void say() //这个方法被显示隐藏了

{

Console.WriteLine("dog say");

}

}

class sheep : animal

{

}

}

3、new 约束:用于在泛型声明中约束可能用作类型参数的参数的类型。举个例子看一下,泛型类中T要求有一个无参的构造函数,代码如下,using System;

using System.Collections.Generic;

namespace ConsoleApplication2

{

public class Employee

{

private string name;

private int id;

public Employee()

{

name = "Temp";

id = 0;

}

public Employee(string s, int i)

{

name = s;

id = i;

}

public string Name

{

get { return name; }

set { name = value; }

}

public int ID

{

get { return id; }

set { id = value; }

}

}

class ItemFactory where T : new()

{

public T GetNewItem()

{

return new T();

}

}

public class Test

{

public static void Main()

{

ItemFactory EmployeeFactory = new ItemFactory();

此处编译器会检查Employee是否具有公有的无参构造函数。

//若没有则会有The Employee must have a public parameterless constructor 错误。

Console.WriteLine("{0}'ID is {1}.", EmployeeFactory.GetNewItem().Name, EmployeeFactory.GetNewItem().ID);

}

}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值