C# C-未处理的异常“System.NullReferenceException”

C# C-未处理的异常“System.NullReferenceException”,c#,exception,error-handling,C#,Exception,Error Handling,当试图查找不存在的注册表项时,它会抛出一个未处理的异常 当checkKey返回null并试图继续时,它会抛出异常 public static string getDirectory(string path, string subpath) { if (checkKey(path).GetValue(subpath) != null) { return checkKey(path).GetValue(subpath).ToString

当试图查找不存在的注册表项时,它会抛出一个未处理的异常

当checkKey返回null并试图继续时,它会抛出异常

public static string getDirectory(string path, string subpath)
    {
        if (checkKey(path).GetValue(subpath) != null)
        {
            return checkKey(path).GetValue(subpath).ToString();
        }
        else
        {
            return null;
        }
    }
我尝试了如果checkKeypath!=null&checkKeypath.GetValuesubpath!=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;
    }
试一试可以解决这个问题,但我觉得我做错了


您好,

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

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

当返回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;
    }
}

总的来说:不要调用一个方法两次。调用它一次,将返回值放入变量中,然后决定如何处理它。如果checkKeypath!=null&&checkKeypath.GetValuesubpath!=null,只有一个&第二部分仍将执行,这将抛出一个错误短路,意味着如果第一个不正确,第二个甚至不会被检查。