0

收到有关“!redirectsDictionary.ContainsKey(autoRedirect.Key)”的警告

asp.net 可能对标有“notnull”属性的实体进行空分配。

只是想知道那是关于什么的?

private static readonly Dictionary<string, Redirect> AutoRedirectsDictionary = new Dictionary<string, Redirect>();

foreach (var r in db.SelectItems("fast:/sitecore/content/Redirects Root//*[@@templatename='Auto Redirect']"))
        {
            GenerateRedirects(Context.Database.GetItem(r.Fields["Root Node"].Value), r["URL Prefix"]);
            foreach (var autoRedirect in AutoRedirectsDictionary)
            {
                if (!string.IsNullOrEmpty(autoRedirect.Key) & !redirectsDictionary.ContainsKey(autoRedirect.Key))
                {
                    //Add to dictionary
                    redirectsDictionary.Add(autoRedirect.Key, autoRedirect.Value);
                }

            }
        }

public static void GenerateRedirects(Item redirectFolder, string urlPrefix)
        {
            if (redirectFolder == null)
                return;

            var childList = redirectFolder.GetChildren();

            foreach (Item child in childList)
            {
                if (Utilities.HasFieldValue(child, FieldToFind))
                {
                    var shortcutUrl = urlPrefix + child.Fields[FieldToFind].Value.ToLower();

                    if (!string.IsNullOrEmpty(shortcutUrl) && !AutoRedirectsDictionary.ContainsKey(shortcutUrl))
                    {
                        AutoRedirectsDictionary.Add(shortcutUrl,
                        new Redirect(String.Empty, child, true));       
                    }
                }
                else
                {
                    GenerateRedirects(child, urlPrefix);
                }
            }
        }
4

1 回答 1

3

这可能与您使用单个&运算符有关。单个&不会使用短路来绕过语句,而是会在评估所有表达式后选择要执行的路径。因此,即使您在!string.IsNullOrEmpty(autoRedirect.Key)ContainsKey 调用之前进行检查,也将首先评估两个表达式,然后确定执行路径。

Edited as I realized I didn't truly answer your specific question (and you may already know this) but !redirectsDictionary.ContainsKey(autoRedirect.Key) will throw an exception if the key is null. Since the datatype for the key is a string there is a possibility it will throw an exception if it is null, hence the warning.

于 2013-01-18T17:02:55.007 回答