英文:
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
英文:
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
答案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..]);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论