本文介绍了如何定义“全局"?变数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我正在开发MVC3应用程序;

我需要一系列变量,其中包含有关特定用户(和用户操作)的必要信息,几乎可以由我的应用程序的任何部分访问.

我想出了创建必要的静态类的解决方案,其中的属性引用了特定的会话变量,这样,一旦设置了它们,它们(理论上)将保持不变,直到被更改/删除为止.例如:

Hi everyone,

I''m developing an MVC3 application;

I need a series of variables which contains necessary info regarding the specific user (and user operations) to be accessed by almost any part of my application.

I came up with the solution of creating the necessary Static Classes, with the properties referring to specific Session Variables, so that once they are set, they''ll (theorically) stay the same until changed/removed; for example:

public static class TestClass
    {

        public static string TestProperty {
            get{
                return HttpContext.Current.Session["MyApplication_TestProperty"].ToString();
            }
            set{
                HttpContext.Current.Session["MyApplication_TestProperty"] = value;
            }
        }

    }



这是一个好的(或至少是体面的)解决方案,还是直接将其发布在耻辱大厅中并寻找另一种方法更好?

有什么建议或更好的解决方案吗?

预先谢谢您,
Alberto



Is this a good (or at least decent) solution, or is it better to directly post it in the Hall of Shame and find another way??

Any suggestion or better solution?

Thank you in advance,
Alberto

推荐答案

public static class TestClass
    {
        const string SessionId = "MyApplication_TestProperty"; //a little better

        public static string TestProperty {
            get{
                return HttpContext.Current.Session[SessionId].ToString();
            }
            set{
                HttpContext.Current.Session[SessionId] = value; //bug fixed.
            }
        }

    }



它可以工作,但不灵活.更通用和通用的方法是使用单人模式,请参见:
http://en.wikipedia.org/wiki/Singleton_pattern [ ^ ],
http://en.wikipedia.org/wiki/Design_pattern_(computer_science) [ ^ ].

这是一篇很好的文章,其中包含C#中的实现示例.我建议您学习如何使用该模式:
http://csharpindepth.com/Articles/General/Singleton.aspx [ ^ ].

祝你好运.

—SA



It will work but is not flexible. More universal and general approach is using the singleton pattern, see:
http://en.wikipedia.org/wiki/Singleton_pattern[^],
http://en.wikipedia.org/wiki/Design_pattern_(computer_science)[^].

This is a good article with implementation samples in C#. I suggest you learn how to use the pattern:
http://csharpindepth.com/Articles/General/Singleton.aspx[^].

Good luck.

—SA



这篇关于如何定义“全局"?变数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 14:56