简体   繁体   中英

Static Class inside Normal class for ASP.Net

I know that making a class static in a ASP.Net project will cause that class's runtime properties to be available to all sessions on the web server.

My question is this: If I declare nested classes static, but the container not, does the sharing of the classes across sessions still apply?

Example:

 public class FooContainer 
    {

        public static class Bar
        {
        }

        public static class dog
        {
        }
    }

Yes; a static nested class has the same behaviour as any other static class. The only time nested classes behave differently is when the outer class is generic type (the nested type is then implicitly generic via the parent, so FooContainer<X>.Bar would be independent of FooContainer<Y>.Bar ).

And just be careful: static for sharing data between sessions is fraught with danger. Synchronize like a paranoid thing. Personally I would need a very good reason to do this... and it needs careful implementation. I only use that approach for things like configuration caching, and even then I'm insanely careful about it.

Ultimately, yes.

The nested static classes are compiled just the same as root-level static classes (Marc wisely notes subtle differences where generics are involved) - the only difference is the qualifying of the path of the type, but this is only natural in any environment and not a side-effect at all.

When I see someone say "static data" and "ASP.NET" in the same sentence all sorts of alerts go off.

Yes, as Marc said, static classes will be static even if they are nested, you just need to call them via the containing class

MyStaticClass.StaticField = 3; ///wont work
MyInstanceClass.MyStaticClass.StaticField = 3; // works

Any instantiable class can have static methods/properties/constructors, making a class explicitly static just has the added benefit that you can't make something non-static my mistake, clarifying the purpose and intent of the class.

But beware, static classes in ASP.net are trully static on an application level, so if you have multiple users, they will all see the same static data, regardless of authorizations, and a change of that data will affect all users who use it.
So a static variable might be the right place to put something that is read once from the db, and then just displayed, ie the current version of the application, or the application's start time, but it's a very wrong place to put user-specific data like language preferences, usernames, etc, etc...

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