How to make a object accessible through all files in C#

二次信任 提交于 2019-12-24 15:14:10

问题


I have a class object which i want to access in all the files in c# project Ofcourse i dont want 'static' qualifiers because i want to serialize this object finally.


回答1:


Make the class public.

You should then be able to create instances wherever you need.

If you want a single instance to be accessible throughout your entire project, I would suggest checking out the Singleton pattern.




回答2:


If you want to you to use only one instance of this class - use one of the most popular pattern Singleton:

http://msdn.microsoft.com/en-us/library/ff650316.aspx

using System;

public class Singleton
{
   private static Singleton instance;

   private Singleton() {}

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


来源:https://stackoverflow.com/questions/7679230/how-to-make-a-object-accessible-through-all-files-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!