在 C++ 中,我们通常会看到和编写如下代码,
Sample sample=new Sample();
if ( sample == NULL )
{
std::cout<<"Memory allocation failed" << std::endl;
}
但是在 C# 中,我很少看到这个:(至少我从未见过这个)
Sample sample = new Sample();
if ( sample == null )
{
Console.WriteLine("Memory allocation failed\n");
}
意味着,在 C# 中,我们很少检查是否new
失败。为什么会这样?它与“在 C# 中,new 永远不会失败”有关吗?C#中是否有这样的事情new
永远不会失败?
如果它失败了,那么为什么这种“检查”在 C# 中如此罕见?我不是在谈论OutOfMemoryException
,毕竟是例外,而不是“检查”。我说的是编码风格。