日期:2014-05-19  浏览次数:20725 次

c# 中的static问题
java中可以在一个类中这样写:
private   static   Map   testMap   =   new   Hashmap();
static{
        testMap.put( "1 "   ,   "1 ");
        testMap.put( "2 "   ,   "2 ");
}

不知道c#中如何写,有知道的朋友帮帮忙

------解决方案--------------------
private static Map testMap = new Hashmap();

在使用的地方写
类名.testMap.put( "1 " , "1 ");
类名.testMap.put( "2 " , "2 ");
------解决方案--------------------
把那几个语句写在静态构造方法里
------解决方案--------------------
是不是需要初始化静态成员?
使用静态构造函数吧。
public class A
{
static Hashtable map = new Hashtable();
static A()
{
map.Add( "1 ", "1 ");
map.Add( "2 ", "2 ");
}

}
或者是这样:

public class B
{
static Hashtable map = new Hashtable();
public static Hashtable Map
{
get
{
if (map.Count < 3)
{
map.Add( "1 ", "2 ");
map.Add( "1 ", "2 ");
}
return Map;
}
}
}
很明显,第一种效率更高一些。