各位好,小弟刚开始学C#.NET不久, 对于在类里定义方法是使用public static helloworld() 还是 public helloworld() 一直有迷惑, 不知道两者都有什么样的优劣性呢?
现在自己基本上都是用第一种方式,这样不用的每次使用时都还要初始化一次类.
呵~~还请各位指教一下

解决方案 »

  1.   

    public static helloworld() -- 静态构造函数
    public helloworld() -- 实例构造函数
      

  2.   

    如果是静态的话就不用实例化外层直接调用了
    比如public static helloworld() 
    外层直接 类名.helloworld()
    而如果你是public helloworld() 
    那么外层调用的时候就必须是   
    类名 cls = new 类名();
    然后cls.helloworld() 了
      

  3.   

    静态构造,只能初始化静态成员.
    如果class里面有static成员,并且你没有声明static的构造函数.系统会自动添加一个static构造函数
      

  4.   

    以上说的都是说明和用法。
    静态成员调用xxClass.helloworld()直接调用。
    非静态成员调用new xxClass().helloworld();
    主要我想说下注意的地方。
    有时某种环境下使用静态方法比较方便,就会将某功能类中的大多数方法做成静态方法,如果太多还是做成非静态成员。

    假设数据库的配置信息这样写是方便些,但是不合理
    public class DataConfig
    {
        public static string Server{get;set;}
        public static string DataBase{get;set;}
        public static string Url{get;set;}
    }
    静态成员大家都知道,在整个应用域中都是共享的
    所以当系统中只对一个数据库操作是没有问题,但是使用多个数据库的时问题就来了。
    看另一个先是满足一个数据库时
    public class DataConfig
    {
        private static DataConfig config=new DataConfig();
        public string Server{get;set;}
        public string DataBase{get;set;}
        public string Url{get;set;}
        public static DataConfig GetConfig(){return config;}
    }
    满足多个数据库时
    public class DataConfig
    {
    //    private static DataConfig config=new DataConfig();
        public string Server{get;set;}
        public string DataBase{get;set;}
        public string Url{get;set;}
        public static DataConfig GetConfig(){return new DataConfig();}
    }
    调用时DataConfig.GetConfig()使用也很方便。
    有人就要问我直接用new DataConfig()也可以啊,在后者时是可以,但是在调用代码的地方都要改成new DataConfig()所以不一定是不正确,而是哪种更合理,以上只是说明注意的地方。