索引器的施用
索引器的使用
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 索引器
{
class Program
{
static void Main(string[] args)
{
Program pr = new Program();
pr[1] = "天马";
pr[2] = "将军";
Console.WriteLine(pr[1]);
Console.WriteLine(pr[2]);
Console.WriteLine(pr["nihao",1,1]);
Console.ReadKey();
}
public string fristName = "你好";
public string secondName = "我好";
/// <summary>
/// 只读的索引器
/// </summary>
/// <param name="name">任意string值</param>
/// <param name="x">任意int的值</param>
/// <param name="y">任意int的值</param>
/// <returns></returns>
public string this[string name,int x,int y]
{
get
{
return name+x+y;
}
}
/// <summary>
/// 创建一个索引器
/// </summary>
/// <param name="id">索引号</param>
/// <returns>返回的是string的值</returns>
public string this[int id]
{
set
{
if(id==1)
{
fristName = value;
}
else if (id == 2)
{
secondName = value;
}
else
{
throw new Exception();
}
}
get
{
if (id == 1)
{
return fristName;
}
else if (id == 2)
{
return secondName;
}
else
{
throw new Exception();
}
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 索引器
{
class Program
{
static void Main(string[] args)
{
Program pr = new Program();
pr[1] = "天马";
pr[2] = "将军";
Console.WriteLine(pr[1]);
Console.WriteLine(pr[2]);
Console.WriteLine(pr["nihao",1,1]);
Console.ReadKey();
}
public string fristName = "你好";
public string secondName = "我好";
/// <summary>
/// 只读的索引器
/// </summary>
/// <param name="name">任意string值</param>
/// <param name="x">任意int的值</param>
/// <param name="y">任意int的值</param>
/// <returns></returns>
public string this[string name,int x,int y]
{
get
{
return name+x+y;
}
}
/// <summary>
/// 创建一个索引器
/// </summary>
/// <param name="id">索引号</param>
/// <returns>返回的是string的值</returns>
public string this[int id]
{
set
{
if(id==1)
{
fristName = value;
}
else if (id == 2)
{
secondName = value;
}
else
{
throw new Exception();
}
}
get
{
if (id == 1)
{
return fristName;
}
else if (id == 2)
{
return secondName;
}
else
{
throw new Exception();
}
}
}
}
}