简体   繁体   中英

Overiding Static Classes in C#

I have the following class with static properties and methods which helps manage users on a website. I want to be able to re-use this class among other projects by overriding some properties.

public class Account {

    public static string sessionName = "Account";
    public static string tableName = "Accounts";

    public static bool isLoggedIn(){

        return HttpContext.Current.Session[sessionName] != null;

    }

    public static bool login(string email, string password){

        //connect to database and return user details from specified table
        DataTable t = Database.login(tableName, email, password);

        DataRow r = t.Rows[0];

        HttpContext.Current.Session[sessionName] = r;

        return true;

    }

    public static object val(string name){

        return ((DataRow)HttpContext.Current.Session[sessionName])[name];

    }

}

This basically logs a user in and stores their details in a DataRow in the session, using a session name defined in the properties.

Is it possible to do something like below to use this class with multiple types of user?

public class WebsiteUser : Account {

    public override string sessionName = "WebsiteUser";
    public override string tableName = "WebsiteUsers";

}

public class TradeUser : Account {

    public override string sessionName = "TradeUser";
    public override string tableName = "TradeUsers";

}

Then call the following code to use each derived class.

if (WebsiteUser.isLoggedIn()){

    //manage website user

}

if (TradeUser.isLoggedIn()){

    //manage trade user

}

No. You can not override static members.

Your idea is good. Just Refactor the code to use instance members and override them.

Or better yet, int his specific case - pass the values as constructor arguments. You are not overriding any logic, you just need to store and return data in fields.

You are confusing concepts: you can override methods, not attributes. Just make a constructor that takes initialization values for the attributes and initializes them accordingly. Besides, that only makes sense if the whole static stuff in gone.

I would:

  • Make sessionName and tableName non-static instance members, initialized in the Account constructor
  • Create several static instances of the Account class, named eg websiteUser and tradeUser
  • Construct these instances using different sessionName and tableName
  • Don't have sublasses of the Account class

Instead of if (WebsiteUser.isLoggedIn()) , the code would look like if (Account.websiteUser.isLoggedIn() .

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