c#接口和new关键字和属性访问器基础收获

时间:2023-03-08 15:39:12

1.interface

对于接口,一把我在项目中会这样使用:

        interface IStudent
{
string Name();
string GoSchool();
}

但是呢,这样有个不好的地方就是Name明显的是要获得姓名的,方法好像有点大,某一天我在书中看到可以变化成这样:

        interface IStudent
{
string Name { get; }
string GoSchool();
} public class Student : IStudent
{
public string Name
{
get { return "许多鱼儿"; }
} public string GoSchool()
{
return "Go School";
}
}

这样代码的可读性是不是更高呢?

2.new

一般new关键字的使用场景是,父类的属性或方法,存在同名,但是不提供重写功能,所以子类可以用new关键字,覆盖父类方法,达到在外部访问该属性或方法时,调用的是子类的属性或方法的目的。

        static void Main(string[] args)
{
TestOne tOne = new TestOne();
TestTwo tTwo = new TestTwo();
Console.WriteLine(tOne.Property);
Console.WriteLine(tTwo.Property);
//print 2 1
} public class Base
{
public string Property = "1";
} public class TestOne : Base
{
public new string Property = "2";
} public class TestTwo : Base
{
private new string Property = "3";
}

注意:TestTwo中使用private的目的是想屏蔽外部对父类Property的访问,不过好像没达到这个目的?有陷阱

3.属性访问器(get,set访问器)

        class Student
{
private string _name; public string Name
{
get { return _name; }
set { _name = value; }
} }

这是一个最基本的属性(公开的,外部可访问的称为属性)访问器,外部可读可字段(内部的,外部访问不到的成为字段)_name的值,但是初学时会有疑惑value是从哪里来的呢?大家看看下面的代码,我们用方法来实现get,set访问器,比如:

            public string Name()
{
return _name;
} public void Name(string value)
{
_name = value;
}

好的,虽然实现了,但是和属性访问器一对比,明显的有点多余,你说是不?所以属性访问器可以这个方法来理解,get访问器相当于有返回值的Name()方法,set访问器相当于带参数value的Name()方法,所以理论上属性访问器就是一个封装过了的方法,什么,你不信?

让你信1:

       interface IStudent
{
//接口中不能有字段,只能有方法
//string Name;编译不通过
string Name { get; }
string GoSchool();
}

让你信2:

        public class Student : IStudent
{
//咱们悄悄的把IStudent的修饰符改一下,^_^
public virtual string Name
{
get { return "许多鱼儿"; }
} public string GoSchool()
{
return "Go School";
}
} public class HighStudent : Student
{
public override string Name
{
get
{
return base.Name;
}
}
}

什么,你还不信?自己蹲墙角画圈去