【问题标题】:C# - unhandled exception "System.NullReferenceException"C# - 未处理的异常“System.NullReferenceException”
【发布时间】:2013-09-04 19:28:32
【问题描述】:

当尝试查找不存在的注册表项时,会引发未处理的异常。

看起来当 checkKey 返回 null 并且它试图继续 .GetValue 它抛出异常。

public static string getDirectory(string path, string subpath)
    {
        if (checkKey(path).GetValue(subpath) != null)
        {
            return checkKey(path).GetValue(subpath).ToString();
        }
        else
        {
            return null;
        }
    }

我试过 if (checkKey(path) != null & checkKey(path).GetValue(subpath) != null) 但这并没有解决问题。

 public static RegistryKey checkKey(string key)
    {
        if (getBaseCurrent64().OpenSubKey(key) != null)
        {
            return getBaseCurrent64().OpenSubKey(key);
        }
        else if (getBaseLocal64().OpenSubKey(key) != null)
        {
            return getBaseLocal64().OpenSubKey(key);
        }
        return null;
    }

try catch 可以解决这个问题,但我觉得我做错了。

亲切的问候,

【问题讨论】:

  • 一般来说:一个方法不要调用两次。调用一次,将返回值放入变量中,然后决定如何处理它。
  • if (checkKey(path) != null && checkKey(path).GetValue(subpath) != null),只有一个&,第二部分仍然会执行,这会引发错误。 &&“短路”,意思是如果第一个不是真的,第二个甚至不会被检查。

标签: c# exception error-handling


【解决方案1】:

您可以在返回 null 时执行 GetValue()。尝试将您的代码更改为

public static string getDirectory(string path, string subpath)
{
    RegistryKey key = checkKey(path);
    if (key != null && key.GetValue(subpath) != null)
    {
        return key.GetValue(subpath).ToString();
    }
    else
    {
        return null;
    }
}

【讨论】:

    【解决方案2】:

    您需要使用逻辑 AND 运算符 (&&) 而不是按位 AND 运算符 (&),请将您的代码更改为:

    if (checkKey(path) != null && checkKey(path).GetValue(subpath) != null)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-17
      • 1970-01-01
      • 1970-01-01
      • 2018-09-03
      • 1970-01-01
      • 2018-07-05
      • 1970-01-01
      相关资源
      最近更新 更多