对象创建问题 [英] problem with object creation

查看:63
本文介绍了对象创建问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将类的对象创建为public. mns,那时我们需要在asp.net中使用oops概念,所以我们需要在每个页面中创建该类的对象,而我只想创建一次,并且所有页面都可以访问它.

i want to create object of class as public. mns whn we use oops concept in asp.net that time we need to create object of that class in each page bt i want create only once and it can be accessible to all pages.

推荐答案



您可以使用Singleton模式的概念.

请参考链接 http://msdn.microsoft.com/en-us/library/ff650316.aspx [ ^ ]用于实现单例模式.

您还可以将类设为静态,然后在第一次调用该类的成员时,将创建该类的对象,并且在整个项目中将使用同一对象.

静态类的示例.
Hi,

You can use the concept of Singleton pattern.

Refer the link http://msdn.microsoft.com/en-us/library/ff650316.aspx[^] for implementing singleton pattern.

You can also make your class static and then when you call member of that class first time the object of that class will be created and the same object will be used through out the project.

Example with Static class.
public static class A
{
  public static int RunMyMethod()
  {
    //int intvar=0;
    //some code
    //return intvar;
  }
}

public class YourPageClass
{
  int result = A.RunMyMethod(); //Here you dont need to write new for creating the obj of static class A it will create object of the class A internally and the same instance will be used through out the project.
}


但是我的建议是使用Singleton模式创建类的单个实例.

来自MSDN的Singleton模式示例.


But my suggestion is to use Singleton pattern to create single instance of the class.

Example of Singleton pattern from MSDN.

public class Singleton
{
   private static Singleton instance;

   private Singleton() {}

   public static Singleton Instance
   {
      get
      {
         if (instance == null)
         {
            instance = new Singleton();
         }
         return instance;
      }
   }
}


通过使用此calass,您将确保仅创建类的一个实例并在整个项目中使用它.


By using this calass you will make sure only one instance of the class will be crated and used through out the project.


这篇关于对象创建问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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