俊生's profile找不到服务器PhotosBlogLists Tools Help
    May 13

    SingleClass

    using System;

    namespace MyForm
    {
     /// <summary>
     /// SingleClass 的摘要说明。
     /// </summary>
     public class SingleClass
     {
      private static int mark = 1;
      private SingleClass()
      {
       mark  += 1;
      }

      private static SingleClass sClass = null;
      public static SingleClass GetSingleClass()
      {
       if (sClass == null)
       {
        sClass = new SingleClass();
       }
       return sClass;
      }

      public int Getmark
      {
       get
       {
        return mark;
       }
      }
     }
    }

    ========================================

    此处构造函数就是不想直接被调用才写成private的,在该类内用new SingleClass是没有问题的吧。

    关于mark的的释放倒是确实要注意的,呵呵。欢迎评论。

    应该是我没写清楚吧,这个就是想实现在一个程序里面只能有个该类的实例的。mark是为了测试用了。:)

     

    Comments (2)

    Please wait...
    Sorry, the comment you entered is too long. Please shorten it.
    You didn't enter anything. Please try again.
    Sorry, we can't add your comment right now. Please try again later.
    To add a comment, you need permission from your parent. Ask for permission
    Your parent has turned off comments.
    Sorry, we can't delete your comment right now. Please try again later.
    You've exceeded the maximum number of comments that can be left in one day. Please try again in 24 hours.
    Your account has had the ability to leave comments disabled because our systems indicate that you may be spamming other users. If you believe that your account has been disabled in error please contact Windows Live support.
    Complete the security check below to finish leaving your comment.
    The characters you type in the security check must match the characters in the picture or audio.

    To add a comment, sign in with your Windows Live ID (if you use Hotmail, Messenger, or Xbox LIVE, you have a Windows Live ID). Sign in


    Don't have a Windows Live ID? Sign up

    Picture of Anonymous
    _Vincent_Chen wrote:
    SingleClass的构造函数应该用public,不然,你
    new SingleClass会出错
    public SingleClass()
    {
    mark += 1;
    }

    还有,要写个虚构函数,减少引用计数器和在最后释放sclass
    ~SingleClass()
    {
    mark -= 1;
    if(0 == mark)
    {
    sClass = null;
    }
    }

    但是如果一次实例化多次调用GetSingleClass()还是会出错,所以不如加个ReleaseSingleClass()方法
    May 17
    Picture of Anonymous
    Belem_Cheung wrote:
    善待受伤的人,呵呵,同意??
    May 16

    Trackbacks

    The trackback URL for this entry is:
    http://justinxiaownerspace.spaces.live.com/blog/cns!AEE6B3A2845872C0!188.trak
    Weblogs that reference this entry
    • None