如何解释C#中的null合并运算符

huangapple go评论67阅读模式
英文:

How to interpret null-coalescing operators in c#

问题

I have been given some code using nullable types, which are new to me (I learnt C# many years ago, in its infancy, and haven't kept up, sorry!)

The code I am trying to understand is

public readonly Trie?[] next = new Trie?[26];

and

var t = next[u] ??= new Trie();
t.insert(p[1..]);

To understand what's going on here, I have tried to rewrite this as

if (next is null)
{
    var t = new Trie();
    t.insert(p[1..]);
}
else
{
    var t = next[u];

    if (t is null)
        t = new Trie();

    t.insert(p[1..]);
}

but it doesn't return the same results when the code is run.

Question 1: is it possible to rewrite this nullable syntax in 'old-school' C#?

Question 2: if so, what's wrong with my interpretation?

If I can answer these, I will be able to start using these types in my own code 如何解释C#中的null合并运算符

英文:

I have been given some code using nullable types, which are new to me (I learnt C# many years ago, in its infancy, and haven't kept up, sorry!)

The code I am trying to understand is

public readonly Trie?[] next = new Trie?[26];

and

var t = next[u] ??= new Trie();
t.insert(p[1..]);

To understand what's going on here, I have tried to rewrite this as

    if (next is null)
    {
         var t = new Trie();
         t.insert(p[1..]);
    }
    else
    {
         var t = next[u];

         if (t is null)
               t = new Trie();

         t.insert(p[1..]);
     }

but it doesn't return the same results when the code is run.

Question 1: is it possible to rewrite this nullable syntax in 'old-school' C#?

Question 2: if so, what's wrong with my interpretation?

If I can answer these, I will be able to start using these types in my own code 如何解释C#中的null合并运算符

答案1

得分: 4

以下是翻译好的部分:

// 检查 next[u] 是否为 null,如果是,则
// 创建并分配一个新的 Trie 实例给它
var t = (next[u] ??= new Trie());

t.insert(p[1..]);

然后,我们可以将其翻译成传统的风格,如下:

if (next[u] == null) 
  next[u] = new Trie();

var t = next[u];

t.insert(p[1..]);
英文:

For given fragment

var t = next[u] ??= new Trie();
t.insert(p[1..]);

let's add parenthesis:

// check if next[u] is null and if it is, 
// create and assign new instance of Trie to it 
var t = (next[u] ??= new Trie());

t.insert(p[1..]);

Then we can translate it int good old style as

if (next[u] == null) 
  next[u] = new Trie();

var t = next[u];

t.insert(p[1..]);

huangapple
  • 本文由 发表于 2023年3月15日 20:43:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/75744881.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定