为什么要使用get和set
因为在代码中存在着私有的值,我们不能在它的私有域外调用这些私有值,若要访问这些私有值,则需要使用get和set。我们可以通过该类中共有的方法来使用私有值。
举一个错误的代码:
// using System;
namespace Keqin
{
class Hutao
{
public static void Main(String[] args)
{
Suo suo = new Suo();
int l = suo.a;//错误
}
}
class Suo
{
private int a = 10;
public int A
{
get { return a; }
}
}
}
因为Suo里的a是用private修饰的私有变量,所有不能直接访问,会报错!
使用get访问私有变量
演示一片代码来访问私有值:
// using System;
namespace Keqin
{
class Hutao
{
public static void Main(String[] args)
{
Suo suo = new Suo();
int l = suo.A;
Console.WriteLine(l);
}
}
class Suo
{
private int a = 10;
public int A
{
get { return a; }
}
}
}
调用get,这样写可以访问Suo里面的私有值a.
使用set和get定义一个索引器
定义一个属性(property)包括提供属性名称。索引器定义的时候不带有名称,但带有 this 关键字,它指向对象实例。下面是菜鸟教程(https://www.runoob.com/csharp/csharp-indexer.html)上解释的语法:
// element-type this[int index]
{
// get 访问器
get
{
// 返回 index 指定的值
}
// set 访问器
set
{
// 设置 index 指定的值
}
}
接下来我来举一个实例:
//using System;
namespace Keqin
{
class Hutao
{
public static void Main(String[] args)
{
Suo suo = new Suo();
int l = suo[1];//get方法
suo[30] = 500;//set方法
}
}
class Suo
{
private int a = 10;
private int[] b = new int[3];
public int this[int t]
{
get
{
Console.WriteLine("这里是get");
Console.WriteLine(t);
return a;
}
set
{
Console.WriteLine("这里是set");
Console.WriteLine(t);
t = value;
Console.WriteLine(value);
}
}
public int A
{
get { return a; }
}
}
}
结果是: