C#中怎么做到这样的stylevar["charset"]下标为字符串的数组?

tuoji 2004-05-03 11:36:02
在PHP中数组下标可以是字符串,比如:stylevar["charset"]
这样的好处是非常便于记忆,不容易出错。请问在C#中怎么用这样的数据表示方法,谢谢!
...全文
41 2 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
gasover 2004-05-03
  • 打赏
  • 举报
回复
namespace Programming_CSharp
{
using System;

// a simplified ListBox control
public class ListBoxTest
{
// initialize the list box with strings
public ListBoxTest(params string[] initialStrings)
{
// allocate space for the strings
strings = new String[256];

// copy the strings passed in to the constructor
foreach (string s in initialStrings)
{
strings[ctr++] = s;
}
}

// add a single string to the end of the list box
public void Add(string theString)
{
strings[ctr] = theString;
ctr++;
}

// allow array-like access
public string this[int index]
{
get
{
if (index < 0 || index >= strings.Length)
{
// handle bad index
}
return strings[index];
}
set
{
strings[index] = value;
}
}

private int findString(string searchString)
{
for (int i = 0;i<strings.Length;i++)
{
if (strings[i].StartsWith(searchString))
{
return i;
}
}
return -1;
}
// index on string
public string this[string index]
{
get
{
if (index.Length == 0)
{
// handle bad index
}

return this[findString(index)];
}
set
{
strings[findString(index)] = value;
}
}


// publish how many strings you hold
public int GetNumEntries()
{
return ctr;
}

private string[] strings;
private int ctr = 0;
}

public class Tester
{
static void Main()
{
// create a new list box and initialize
ListBoxTest lbt =
new ListBoxTest("Hello", "World");

// add a few strings
lbt.Add("Who");
lbt.Add("Is");
lbt.Add("John");
lbt.Add("Galt");

// test the access
string subst = "Universe";
lbt[1] = subst;
lbt["Hel"] = "GoodBye";
// lbt["xyz"] = "oops";

// access all the strings
for (int i = 0;i<lbt.GetNumEntries();i++)
{
Console.WriteLine("lbt[{0}]: {1}",i,lbt[i]);
} // end for
} // end main
} // end tester
} // end namespace
gasover 2004-05-03
  • 打赏
  • 举报
回复
用索引器

62,243

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧