How to make a object accessible through all files

2019-08-08 03:44发布

问题:

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;
      }
   }
}


标签: c# class object