有关使用静态类缓存系统配置参数的问题

wapit 2010-01-06 11:19:37
不知道我这样说能不能描述清楚这个问题.


//我想定义一个这样的Config类, 用来在系统启动时从数据库中读入系统配置
public class Config
{}

public class Test
{
private xxx()
{
string name=Config["name"]; //想实现这样的代码调用. 而不是name=Config.Get("name");
//因为Config里面内容在启动时一次性从数据库读入了,很多地方应用到.
//如果每次使用都要new出来一个新实例的话势必造成不必要的开销.
}
}
...全文
116 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
fihuang 2010-01-07
  • 打赏
  • 举报
回复
用静态变量,就启动的时候读一次就行了。
wapit 2010-01-07
  • 打赏
  • 举报
回复
现在我怀疑这个问题要无解了. 因为当我写出
string xx = Config["name"];
这句语句时, 编译器直接提示:
'Config' is a 'type' but is used like a 'variable'

莫非语法上就不支持这样干?
wapit 2010-01-07
  • 打赏
  • 举报
回复
又沉了......

还有这个贴子, 谁去接下分? 我好结贴......
http://topic.csdn.net/u/20100106/01/e1b58d2a-c74f-420c-b990-5bb83dcccaad.html
wapit 2010-01-07
  • 打赏
  • 举报
回复
加分结贴了. 谢谢各位!
wapit 2010-01-07
  • 打赏
  • 举报
回复
[Quote=引用 10 楼 acqy 的回复:]
静态类是不能加索引的,index的定义需要this关键字,而在静态类上,this是没有意义的。
不知楼主为何一定想要index来做,是为了代码好看些么?[/Quote]
呵呵. 正解. 就是想让代码好看点.
现在用两个方法实现了
public string GetValue(string key)
public void SetValue(string key,string value)

算了. 不钻牛角尖了, 结贴.
acqy 2010-01-07
  • 打赏
  • 举报
回复
静态类是不能加索引的,index的定义需要this关键字,而在静态类上,this是没有意义的。
不知楼主为何一定想要index来做,是为了代码好看些么?其实是可以用方法替代的。楼主看下面的代码:

public class MyConfig
{
private List<int> configs = new List<int>();

private static readonly MyConfig instance = new MyConfig();

private MyConfig() { }
static MyConfig() { }

public static MyConfig Instance { get { return instance; } }

public int this[int idx]
{
get
{
return configs[idx];
}
set
{
configs[idx] = value;
}
}
}


那么使用的时候就是:

int p = MyConfig.Instance[10];


这样用到了index,但恐怕比使用方法不会好看到哪里去。
wapit 2010-01-07
  • 打赏
  • 举报
回复
刚GOOGLE这个问题时居然搜到这个帖子了. GOOGLE太牛了......
wapit 2010-01-07
  • 打赏
  • 举报
回复
  public string this[string key]
{
get
{
//return ...
}
set
{
//...;
}
}

这样时, 编译器给出错误: cannot declare indexers in a static class
wapit 2010-01-07
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 mngzilin 的回复:]
public static class Config
{
}
[/Quote]
然后呢? 下面的this[]索引如何定义?
我试过这些, 都不行. 语法就不对:
public string this[string key]
public string Config[string key]
public static string this[string key]
public static Config[string key]
mngzilin 2010-01-07
  • 打赏
  • 举报
回复
public static class Config
{

}
wapit 2010-01-06
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 lcl_data 的回复:]
["name"]这个就是索引
用关键字this[]
[/Quote]
我现在就是用了this. 但问题是用this必须要实例化才能用.
必须Config c=new Config();之后才能c["name"];

我想看看还有没有别的办法.
十八道胡同 2010-01-06
  • 打赏
  • 举报
回复
["name"]这个就是索引
用关键字this[]

110,545

社区成员

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

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

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