简体   繁体   English

具有静态成员和公共构造函数的类是否是静态类?

[英]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 ? 如果我有一个未标记为static的类,但确实具有static成员变量,这是否会使该类本身成为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. 另外,在网页的Web应用程序中,我调用静态类,并将其分配给要在页面中使用的静态成员变量。 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? 还是GC不会在更长的时间内收集它?

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. 编辑:ASP.NET用户会话与.NET中的内存管理关系不大,除非某些数据确实存储在其会话中-基本上这只是对该对象的强引用。

A static variable will prevent the object it refers to from being garbage collected while the AppDomain it's part of is still alive. 静态变量将防止所引用的对象在它所属的AppDomain仍然存在时被垃圾回收。

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. 关于customers变量-这将仅防止List<CustUser>被垃圾回收,只要该变量被认为是“活动的”即可-这将取决于它是什么类型的变量以及如何使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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