new的使用
new可作为操作符或者修饰符,作为修饰符时,仅允许在嵌套类声明时使用,表明类中影藏了由基类中继承而来的与基类中同名的成员
解释:比如你父类里有一个方法叫 Method()
然后你子类里也有一个方法叫 Method()
原本,因为子类的继承关系,他自己就会有一个Method()了,然后你又新定义了一个,于是程序编译的时候,不知道这个Method()到底用哪一个,所以你在子类里使用new谓语以后,就会把子类中原有的(继承父类的)Method()改由你后写的那个替换掉
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class baseclass
{
public class testclass
{
public int x = 20;
public int y;
}
}
public class deriveclass : baseclass
{
new public class testclass //由基类继承而来的同名成员 用new来实现
{
public int x = 10;
public int y;
public int z;
}
public static void Main()
{
testclass s1 = new testclass();
baseclass.testclass s2 = new baseclass.testclass();
Console.WriteLine("s1的值:{0}", s1.x);
Console.WriteLine("s2的值:{0}", s2.x); //记住每个write从{0}
Console.ReadLine();
}
}
抽象属性的抽象类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public enum sex { women, man};
abstract public class person
{
protected string name;
protected sex xb;
public abstract string Name //抽象属性
{
get;
set;
}
public abstract sex sex //抽象属性
{
get;
set;
}
}
class student : person
{
string xh;
decimal score;
public override string Name //必须重写
{
get { return name; }
set { name = value; }
}
public override sex sex //必须重写
{
get
{
//throw new NotImplementedException();
return xb;
}
set
{
xb = value;
//throw new NotImplementedException();
}
}
public string xuehao
{
get { return xh; }
set { xh = value; }
}
public decimal Score
{
get { return score; }
set { score = value; }
}
}
class test
{
public static void Main()
{
student stu = new student(); //通过属性设置值
stu.xuehao = "0708009";
stu.Name = "张三";
stu.sex = sex.man;
stu.Score = 80.0m;
Console.WriteLine("学号={0}",stu.xuehao); //通过属性输出值
Console.WriteLine("姓名={0}",stu.Name);
Console.WriteLine ("成绩={0}",stu.Score );
Console .ReadLine ();
}
}