C# : So if a static class is bad practice for storing global state info, what's a good alternative that offers the same convenience?

前端 未结 3 1951
野趣味
野趣味 2020-12-24 02:13

I\'ve been noticing static classes getting a lot of bad rep on SO in regards to being used to store global information. (And global variables being scorned upon in general)

3条回答
  •  半阙折子戏
    2020-12-24 02:32

    I'd try a different approach. The static data class is going to get you in trouble -- this is from experience. You could have a User object (see @Robert Paulson's answer for a great way to do this) and pass that to every object as you construct it -- it might work for you but you'll get a lot template code that just repeats everywhere.

    You could store all your objects in a database / encrypted file with the necessary permissions and then dynamically load all of them based on your Users permissions. With a simple admin form on the database, it's pretty easy to maintain (the file is a little bit harder).

    You could create a RequiresAdminPermissionAttribute object to apply to all your sensitive objects and check it at run-time against your User object to conditionally load to objects.

    While the route you're on now has merit, I think there are some better options to try.

提交回复
热议问题