我有一个私人构造函数我可以使用方法外面类如何......? [英] I Hv A Private Constructor Can I Use Method Out Side The Class An How...?

查看:66
本文介绍了我有一个私人构造函数我可以使用方法外面类如何......?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我更新,我在面试中寻找很多时间

i m fresher i m seeking many time from this question in interview

推荐答案

实例化私有构造函数的唯一真正方法是从类本身内部。通过这样的方式将这被误用为实现单例模式的方法是很常见的:
The only real way to instantiate a private constructor is from inside the class itself. It's common to see this being misused as a way to achieve a singleton pattern by doing something like this:
public class MyFactory
{
  private int _threadCount;
  private static MyFactory _instance;
  private MyFactory()
  {
    _threadCount = 10;
  }
  public static MyFactory Instance
  {
    get
    {
      if (_instance == null)
      {
        // As this belongs to the same object, we can
        // new it up here.
        _instance = new MyFactory();
      }
      return _instance;
    }
  }
}


我给出了一个调用类具有私有构造函数的类方法的示例。 br />


1.创建一个具有私有构造函数的类



I am giving a example that calls method of class that class has private constructor.

1. Create a class that has private constructor

using System;

namespace SingletonExample
{
   public  class User
    {
       private static User user = null;
       private static readonly object padlock = new object();
       private User()
       {
       }

       public static User GetInstance()
       {
           lock (padlock)
           {
               if (user == null)
               {
                   user = new User();
               }
               return user;
           }
       }

       public void GetMessage()
       {
           Console.WriteLine("I am method of class user");
       }

    }
}







2.在执行程序中调用方法






2. call the method in execution program

using System;

namespace SingletonExample
{
    class Program
    {
        static void Main(string[] args)
        {
            User user = User.GetInstance();
            user.GetMessage();
            Console.ReadKey();
        }
    }
}





如果您想了解更多信息,请阅读本文



http://csharpindepth.com/articles/general/singleton.aspx [ ^ ]


请参阅wiki: Singleton Pattern [ ^ ]
See wiki: Singleton Pattern[^]


这篇关于我有一个私人构造函数我可以使用方法外面类如何......?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆