我喜欢null-coalescing运算符,因为它可以很容易地为可空类型分配默认值.
int y = x ?? -1;
Run Code Online (Sandbox Code Playgroud)
这很好,除非我需要做一些简单的事情x.例如,如果我想检查Session,那么我通常最终不得不写更详细的东西.
我希望我能做到这一点:
string y = Session["key"].ToString() ?? "none";
Run Code Online (Sandbox Code Playgroud)
但是你不能因为在.ToString()null检查之前调用了gets,所以如果Session["key"]为null 则它会失败.我最终这样做了:
string y = Session["key"] == null ? "none" : Session["key"].ToString();
Run Code Online (Sandbox Code Playgroud)
在我看来,它比三线替代方案更有效,也更好:
string y = "none";
if (Session["key"] != null)
y = Session["key"].ToString();
Run Code Online (Sandbox Code Playgroud)
尽管有效,但如果有更好的方法,我仍然很好奇.似乎无论我总是要引用Session["key"]两次; 一次检查,再次检查.有任何想法吗?
在PowerShell中是否存在空合并运算符?
我希望能够在powershell中执行这些c#命令:
var s = myval ?? "new value";
var x = myval == null ? "" : otherval;
Run Code Online (Sandbox Code Playgroud) 虽然我正在研究委托其是实际上是一个抽象类中Delegate.cs,我看到了下面的方法中,我不明白
?它已经是一个引用(类)类型?[]? 参数的含义你能解释一下吗?
public static Delegate? Combine(params Delegate?[]? delegates)
{
if (delegates == null || delegates.Length == 0)
return null;
Delegate? d = delegates[0];
for (int i = 1; i < delegates.Length; i++)
d = Combine(d, delegates[i]);
return d;
}
Run Code Online (Sandbox Code Playgroud) .net c# null-coalescing-operator null-coalescing nullable-reference-types
null coalescing大致翻译为 return x, unless it is null, in which case return y
我经常需要 return null if x is null, otherwise return x.y
我可以用 return x == null ? null : x.y;
不错,但null中间总是困扰我 - 这似乎是多余的.我更喜欢这样的东西return x :: x.y;,::只有在它之前的东西不是的时候才会评估null.
我认为这几乎与null合并相反,有点简洁,内联null检查,但我[ 几乎 ]确定在C#中没有这样的运算符.
(我知道我可以用C#编写一个方法;我使用return NullOrValue.of(x, () => x.y);,但如果你有更好的东西,我也希望看到它.)
c# syntax programming-languages operators null-coalescing-operator
问题:price = co?.price ?? 0,以下代码中的行给出了上述错误.但如果我?从co.?它删除它工作正常.我试图按照此MSDN例如,他们使用的是?上线select new { person.FirstName, PetName = subpet?.Name ?? String.Empty };所以,看来我需要了解什么时候使用?与??和何时不.
错误:
表达式树lambda可能不包含空传播运算符
public class CustomerOrdersModelView
{
public string CustomerID { get; set; }
public int FY { get; set; }
public float? price { get; set; }
....
....
}
public async Task<IActionResult> ProductAnnualReport(string rpt)
{
var qry = from c in _context.Customers
join ord in _context.Orders
on …Run Code Online (Sandbox Code Playgroud) 在角度2中等效的空合并运算符(??)是什么.
在C#中我们可以执行一个操作:
string str = name ?? FirstName ?? "First Name is null";
Run Code Online (Sandbox Code Playgroud) 是否有内置的VB.NET等效于C#null合并运算符?
我在c#6中编写了一段代码,并且出于一些奇怪的原因,这是有效的
var value = objectThatMayBeNull?.property;
Run Code Online (Sandbox Code Playgroud)
但这不是:
int value = nullableInt?.Value;
Run Code Online (Sandbox Code Playgroud)
不工作我的意思是我得到一个编译错误说Cannot resolve symbol 'Value'.知道为什么null条件运算符?.不起作用吗?
如何编写以下方案的简写?
get
{
if (_rows == null)
{
_rows = new List<Row>();
}
return _rows;
}
Run Code Online (Sandbox Code Playgroud) 可能重复:
?? Null Coalescing Operator - >合并是什么意思?
C#中两个问号共同意味着什么?
我在这里找不到这个问题所以我想我会问它.双重问号在C#中有什么作用?
例:
x = y ?? z;
Run Code Online (Sandbox Code Playgroud)