简体   繁体   中英

Is a class with static members and a public constructor a static class?

If I have a class that is not marked static , but it does have static member variables, does this make the class itself static ? It's being used in code like it is, but it has a public constructor. I thought they can only have private constructors?

Also, in a web application in a web page I make a call to a static class and assign it to a static member variable to be used in the page. If a user leaves the page will the static member variable remain in memory? I'm thinking just for the duration of that user's session, correct? Or would GC refrain from collecting it for some longer period of time?

Ok here's some code:

 public class CustomerManager
{

    private static MyFactory _customerFactory = MyFactory.GetInstance();

    public CustomerManager()
    { }

     public static List<CustUser> GetCustomersByWebRequest(int iClientID, string sEmployeeNumber)

It is being called in another class that is static like so:

 List<CustUser> customers = CustomerManager.GetCustomersByWebRequest(1, "23434");

and this is in production.

No, it's entirely plausible for a non-static class to contain static members.

Static classes don't have any instance constructors. Non-static classes have public instance constructors by default, but you can prevent instantiation "from the outside" with a private instance constructor.

EDIT: ASP.NET user sessions have little to do with memory management in .NET, unless some data is definitely stored in their session - which basically just acts as a strong reference to that object.

A static variable will prevent the object it refers to from being garbage collected while the AppDomain it's part of is still alive.

Regarding the customers variable - that will only prevent the List<CustUser> being garbage collected as long as the variable is considered "live" - and that will depend on what sort of variable it is and how it's being used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM