简单问题,简单分数。如何在C#中建立数组?

hproof 2003-04-07 03:28:50
类似的代码在C++中应该如下:

struct Table
{
  int code;
  PFUN fun;
}tb[]=
{
  1,func1,
  2,func2,
  3,func3
};

int Dofun(int code)
{
  for(int i=0; i<sizeof(tb)/sizeof(tb[0]); i++)
  {
    if(tb[i].code == c)
    {
      (*tb[i].fun)();
      break;
    }
  }
}

该函数根据输入的代码号,调用相应的函数,只须修改表格部分,就可以实现很多的功能。
在C#中面临的问题是无法建立静态的数组,可能需要如下的步骤:
for(int i=0; i<tb.Length; i++)
{
tb[i] = new Table(...);
}

但这是一个Table表格类,它的用途是只要在定义该表格的地方进行修改,就可以在不修改函数代码的前提下完成了新的功能。如果用C#临时生成的话,,,好象太麻烦了。。

//别告诉我用数据库!
...全文
65 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
hproof 2003-04-07
  • 打赏
  • 举报
回复
,,,,我真想谁都不给分,,这么简单的问题也值100分??。
hproof 2003-04-07
  • 打赏
  • 举报
回复
struct StringTable
{
public String code;
public String str;
public String htmlcode;
public StringTable(String c, String s, String h){
code=c; str=s; htmlcode=h;
}
};
public class MyConvert
{
static StringTable[] table =
{
new StringTable ("_z", "_", "_"),
new StringTable ("_a", "&" , "&"),
new StringTable ("_b", "\"", """),
new StringTable ("_c", "'", "'"),
new StringTable ("_d", "<", "<"),
new StringTable ("_e", ">", ">"),
new StringTable ("_f", " ", " "),
new StringTable ("_g", "?", "á")
};
qingren 2003-04-07
  • 打赏
  • 举报
回复
当然,如果code是关键字,并且只有一个属性,用hashtable更好一些
不用去循环查找函数名称
qingren 2003-04-07
  • 打赏
  • 举报
回复
用动态数组ArrayList
class Table
{
  int code;
  string fun;
}
ArrayList a=new ArrayList();

void InitArray()
{
a.Add(new Table(1,"func1"));
a.Add(new Table(2,"func2"));
a.Add(new Table(3,"func3"));
}
int Dofun(int code)
{
  foreach(Table tb in a)
  {
    if(tb.code == c)
    {
      Call(tb.fun);
      break;
    }
  }
}
在c#中,用反射机制根据名称调用函数Call
xumahua 2003-04-07
  • 打赏
  • 举报
回复
up
yqdeng 2003-04-07
  • 打赏
  • 举报
回复
用hashtable吧
showflow 2003-04-07
  • 打赏
  • 举报
回复
用hashtable行不行呀
zwztu 2003-04-07
  • 打赏
  • 举报
回复
关注
rqxiang 2003-04-07
  • 打赏
  • 举报
回复
up

110,538

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

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