What is this operator, "??"

This question already has an answer here:

  • What do two question marks together mean in C#? 16 answers

  • Well yeah that looks like an error. The code is looking whether Context.ContentDatabase or Context.Database aren't null , and then continues to use the former, even if it was null .

    The code should look like this:

    var database = Context.ContentDatabase ?? Context.Database;
    
    if (fieldConfiguration == null && database != null)
    {
        Item obj = database.SelectSingleItem(
            string.Format("//*[@@templateid='{0}' and @@key='{1}']", 
                (object) TemplateIDs.TemplateField, (object) fieldName));
    }
    

    Where it stores the database in a separate variable using the null-coalescing operator and then operates on that, if it isn't null .

    So you should contact the team who provides this library and file a bug with them.


    (Context.ContentDatabase ?? Context.Database) expressions end result is Context.ContentDatabase if Context.ContentDatabase is not null, otherwise it'll be Context.Database . The null-coalesce operator is a step forward to terse null checks.

    Docs: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-conditional-operator


    Assuming Context.ContentDatabase and Context.Database are same types. The below code should work.

    var contentDatabase = Context.ContentDatabase ?? Context.Database;
    if (fieldConfiguration == null && contentDatabase != null)
    {
    Item obj = contentDatabase.SelectSingleItem(
        string.Format("//*[@@templateid='{0}' and @@key='{1}']", 
            (object) TemplateIDs.TemplateField, (object) fieldName));
    }
    
    链接地址: http://www.djcxy.com/p/53852.html

    上一篇: >合并意味着什么?

    下一篇: 这个操作员是什么,“??”