Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在c中存储全局变量?_C#_Asp.net_Caching_Static Members - Fatal编程技术网

C# 在c中存储全局变量?

C# 在c中存储全局变量?,c#,asp.net,caching,static-members,C#,Asp.net,Caching,Static Members,我基本上创建了一个类,当用户登录到一个网站时,它会查询数据库,并在列表中存储一些设置,这样我就有了密钥/对值 这样做的原因是因为我希望始终能够访问这些设置,而无需再次访问数据库 我将它们放在一个类中,通过SQL查询遍历字段,并将它们添加到列表中 然后如何从应用程序的另一部分访问这些变量?还是有更好的方法?我说的是服务器端,而不是真正的客户端 以下是我目前所拥有的一个例子: public static void createSystemMetaData() { string constri

我基本上创建了一个类,当用户登录到一个网站时,它会查询数据库,并在列表中存储一些设置,这样我就有了密钥/对值

这样做的原因是因为我希望始终能够访问这些设置,而无需再次访问数据库

我将它们放在一个类中,通过SQL查询遍历字段,并将它们添加到列表中

然后如何从应用程序的另一部分访问这些变量?还是有更好的方法?我说的是服务器端,而不是真正的客户端

以下是我目前所拥有的一个例子:

public static void createSystemMetaData()
{
    string constring = ConfigurationManager.ConnectionStrings["Test"].ConnectionString;
    SqlConnection sql = new SqlConnection(constring);
    sql.Open();

    SqlCommand systemMetaData = new SqlCommand("SELECT * FROM SD_TABLES", sql);
    //Set Modules
    using (SqlDataReader systemMetaDataReader = systemMetaData.ExecuteReader())
    {
        while (systemMetaDataReader.Read())
        {
            var name = systemMetaDataReader.GetOrdinal("Sequence").ToString();
            var value = systemMetaDataReader.GetOrdinal("Property").ToString();
            var Modules = new List<KeyValuePair<string, string>>();
            Modules.Add(new KeyValuePair<string, string>(name, value));
        }
    }
}

谢谢

假设您在IIS下使用ASP.NET,则类的任何静态属性都将在应用程序池的生命周期内保留

因此,一个非常简单的类可能如下所示:

public static class MyConfigClass
{
    public static Lazy<Something> MyConfig = new Lazy<Something>(() => GetSomethings());

    public static Something GetSomethings()
    {
        // this will only be called once in your web application
    }
}

对于较少的用户,您可以按照Bob的建议使用SessionState,但是对于较多的用户,您可能需要移动到状态服务器或每次从数据库加载状态服务器。

正如其他人所指出的,将这些值保存在全局内存中的风险在于这些值可能会更改。此外,全局变量是一个糟糕的设计决策,因为最终可能会导致应用程序的各个部分读取和写入这些值,这使得调试问题比需要的更困难


通常采用的解决方案是将数据库访问封装在facade类中。如果希望避免每次请求都命中数据库,则该类可以缓存这些值。此外,由于更改也是通过facade路由的,因此它知道数据何时更改,并可以清空其缓存,从而在发生这种情况时强制重新读取数据库。作为一个额外的好处,可以模拟facade来测试代码,而不涉及数据库访问。众所周知,单元测试非常困难。

从外观上看,您使用的是通用值,而不考虑用户,因此在这里使用一个:

确保在web.config中为名称测试设置了数据库依赖项

public static class CacheData {

  public static List<KeyValuePair<string,string>> GetData() {
    var cache = System.Web.HttpContext.Current.Cache;
    SqlCacheDependency SqlDep = null; 
    var modules = Cache["Modules"] as List<KeyValuePair<string,string>>;
    if (modules == null) { 

        // Because of possible exceptions thrown when this 
        // code runs, use Try...Catch...Finally syntax. 
        try { 
            // Instantiate SqlDep using the SqlCacheDependency constructor. 
            SqlDep = new SqlCacheDependency("Test", "SD_TABLES"); 
        } 

        // Handle the DatabaseNotEnabledForNotificationException with 
        // a call to the SqlCacheDependencyAdmin.EnableNotifications method. 
        catch (DatabaseNotEnabledForNotificationException exDBDis) { 
                SqlCacheDependencyAdmin.EnableNotifications("Test"); 
        } 

        // Handle the TableNotEnabledForNotificationException with 
        // a call to the SqlCacheDependencyAdmin.EnableTableForNotifications method. 
        catch (TableNotEnabledForNotificationException exTabDis) { 
                SqlCacheDependencyAdmin.EnableTableForNotifications("Test", "SD_TABLES"); 

       } 
       finally { 
            // Assign a value to modules here before calling the next line
            Cache.Insert("Modules", modules, SqlDep); 
        } 
      }
      return modules;
    }

这就是ASP.NET?您将需要查看每个用户或是ASP.NET好的,非常感谢。我目前正在使用会话,但我认为这样的变量可能是一个更好的主意,因为我要存储很多不同的设置。为什么不每次都要转到数据库?通常的原因是性能问题,但除非您确实存在性能问题,否则我建议您不要这样做。稍后,您可能会发现用户有时希望更改这些值,以便每次重新加载它们会更好。您并没有关闭Sql连接。@realtek,使用ASP.NET,您可以使用静态变量,但会话状态或应用程序状态是更好的方法,甚至是缓存。但是,您可以创建一个类来为您处理检索,这样您就不必
public static class CacheData {

  public static List<KeyValuePair<string,string>> GetData() {
    var cache = System.Web.HttpContext.Current.Cache;
    SqlCacheDependency SqlDep = null; 
    var modules = Cache["Modules"] as List<KeyValuePair<string,string>>;
    if (modules == null) { 

        // Because of possible exceptions thrown when this 
        // code runs, use Try...Catch...Finally syntax. 
        try { 
            // Instantiate SqlDep using the SqlCacheDependency constructor. 
            SqlDep = new SqlCacheDependency("Test", "SD_TABLES"); 
        } 

        // Handle the DatabaseNotEnabledForNotificationException with 
        // a call to the SqlCacheDependencyAdmin.EnableNotifications method. 
        catch (DatabaseNotEnabledForNotificationException exDBDis) { 
                SqlCacheDependencyAdmin.EnableNotifications("Test"); 
        } 

        // Handle the TableNotEnabledForNotificationException with 
        // a call to the SqlCacheDependencyAdmin.EnableTableForNotifications method. 
        catch (TableNotEnabledForNotificationException exTabDis) { 
                SqlCacheDependencyAdmin.EnableTableForNotifications("Test", "SD_TABLES"); 

       } 
       finally { 
            // Assign a value to modules here before calling the next line
            Cache.Insert("Modules", modules, SqlDep); 
        } 
      }
      return modules;
    }