C#索引器简单实例代码
public class Fruit
{
string peach = "a round juicy fruit that has a soft yellow or red skin and a large hard seed in the center, or the tree that this fruit grows on";
string orange = "a round fruit that has a thick orange skin and is divided into parts inside";
string banana = "a long curved tropical fruit with a yellow skin";
string apple = "a hard round fruit that has red, light green, or yellow skin and is white inside ";
public string this[string fruitName]
{
get
{
switch (fruitName)
{
case "peach":
return peach;
case "orange":
return orange;
case "banana":
return banana;
case "apple":
return apple;
default:
throw new Exception("wrong fruit name");
}
}
set
{
switch (fruitName)
{
case "peach":
peach = value;
break;
case "orange":
orange = value;
break;
case "banana":
banana = value;
break;
case "apple":
apple = value;
break;
default:
throw new Exception("wrong fruit name");
}
}
}
}
class Program
{
static void Main(string[] args)
{
Fruit f = new Fruit();
//关联数组的方式访问get方法
Console.WriteLine(f["peach"]);
//关联数组的方式访问set方法
f["peach"] = "I like to eat peach.";
Console.WriteLine(f["peach"]);
Console.ReadLine();
}
}
相关文章
C# 使用EntityFramework CodeFirst 创建PostgreSQL数据库的详细过程
这篇文章主要介绍了C#使用EntityFramework CodeFirst创建PostgreSQL数据库的过程,本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2023-07-07
详解c#中Array,ArrayList与List<T>的区别、共性与相互转换
本文详细讲解了c#中Array,ArrayList与List<T>的区别、共性与相互转换,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2021-12-12


最新评论