繁体   English   中英

如何使用可为空的吸气剂?

[英]How to use a getter with a nullable?

我正在从数据库中读取一堆查询。 我有一个查询无法关闭的问题,因此我添加了CommandTimeout。 现在,每个查询在每次运行时都从配置文件中读取。 我如何使用静态nullable和getter使代码仅从配置文件缓存int一次。 我正在考虑采取以下措施:

static int? var;
get{ var = null;
    if (var.HasValue)
    ...(i dont know how to complete the rest)

我的实际代码:

private object QueryMethod(string item)
{
    using (SqlConnection connection = new SqlConnection(item))
    {
        connection.Open();

        using (SqlCommand sql = new SqlCommand())
        {
            AddSQLParms(sql);
            sql.CommandTimeout = 30;
            sql.CommandText = _cmdText;
            sql.Connection = connection;
            sql.CommandType = System.Data.CommandType.Text;

            sql.ExecuteNonQuery();
        }
        connection.Close();
    }
    return false;
}

第一:不要称它为var

我们称它为cached_value

static int? cached_value;

get { return cached_value ?? chached_value = your_logic_here }

这样,第一次调用它时,如果它为null,它将初始化该字段。 下次调用getter时,您将仅获得所需的值。

您可以使用Lazy<T>类尝试类似的方法:

public static class ConfigCache
{
    private static Lazy<int> connectionTimeout =
        new Lazy<int>(() => int.Parse(
            ConfigurationManager.AppSettings["connectionTimeout"]));

    public static int ConnectionTimeout
    {
        get { return connectionTimeout.Value; }
    }
}

用法:

sqlCmd.CommandTimeout = ConfigCache.ConnectionTimeout;

听起来就像您在询问如何使用Nullable变量。

static int? val;
get{ 
    if (var.HasValue)
    {
      return val.Value;
    }
    else {
       val = GetValFromConfig();
       return val.Value;
    }
} 

var是C#中的关键字

var是系统关键字-请勿使用

V1-在此版本中,您希望config具有值,否则将发生错误

static int? _timeout = null;

private static int GetTimeout()
{
    if (_timeout != null) return (int)_timeout;
    _timeout = GetTimeoutFromConfig();
    return (int)_timeout;
}

V2-在此版本中,如果config为空,则将使用默认值

static int? _timeout = null;
private const int def_timeout = 120;   

private static int GetTimeout()
{
    if (_timeout != null) return (int)_timeout;
    int? to = GetTimeoutFromConfig();
    _timeout = (to ?? def_timeout); 

    return (int)_timeout;
}

从配置转换

private int? GetTimeoutFromConfig()
{
    int val;
    bool converted = int.TryParse(ConfigurationManager.AppSettings["TimeoutValue"], out val);

    return (converted ? val : null);
} 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM