如果C#允许一个?? =运算符,那将是非常好的.我发现自己经常写下面的内容:
something = something ?? new Something();
Run Code Online (Sandbox Code Playgroud)
我宁愿这样写:
something ??= new Something();
Run Code Online (Sandbox Code Playgroud)
思考?新的语言扩展总是存在争议的本质.
C#null合并运算符是否有C++等价物?我在代码中进行了太多的空检查.所以正在寻找一种减少空代码量的方法.
如果我有类似以下的代码:
while(myDataReader.Read())
{
myObject.intVal = Convert.ToInt32(myDataReader["mycolumn"] ?? 0);
}
Run Code Online (Sandbox Code Playgroud)
它抛出错误:
无法将对象从DBNull强制转换为其他类型.
定义intVal为可空int不是一个选项.有没有办法让我做到以上几点?
我刚试过以下内容,想法是连接两个字符串,用空字符串替换空值.
string a="Hello";
string b=" World";
Run Code Online (Sandbox Code Playgroud)
- 调试(有趣的是?是打印,并不完全有助于提高可读性......)
? a ?? "" + b ?? ""
Run Code Online (Sandbox Code Playgroud)
- >"你好"
正确的是:
? (a??"")+(b??"")
"Hello World"
Run Code Online (Sandbox Code Playgroud)
我有点期待"Hello World",或者只是"世界",如果a为null.显然这是运算符优先级的todo,可以通过括号来克服,是否存在记录此新运算符的优先顺序的任何位置.
(意识到我应该使用stringbuilder或String.Concat)
谢谢.
我开始真的很喜欢C#的?运营商.而且我很习惯这样一个事实:在某些语言中有一些方便的东西,它最有可能也在Perl中.
但是,我找不到?? 相当于Perl.有没有?
可能重复:
VB.NET中是否有条件三元运算符?
大家好,我们可以在VB.NET中使用Coalesce运算符(??)和条件三元运算符(:),就像在C#中一样?
我有以下内容,但它失败了NullReferenceException:
<td>@item.FundPerformance.Where(xx => fund.Id == xx.Id).FirstOrDefault().OneMonth ?? -</td>
Run Code Online (Sandbox Code Playgroud)
OneMonth 被定义为
public virtual decimal? OneMonth { get; set; }
Run Code Online (Sandbox Code Playgroud)
并且在失败时它的值为null.
我认为Null Coalesce运算符会测试它是否为null,如果是,则将值返回给运算符右侧?
为了使这项工作,我需要改变什么?
NullReferenceException当我运行此代码时,我发现了一个意外,省略了fileSystemHelper参数(因此将其默认为null):
public class GitLog
{
FileSystemHelper fileSystem;
/// <summary>
/// Initializes a new instance of the <see cref="GitLog" /> class.
/// </summary>
/// <param name="pathToWorkingCopy">The path to a Git working copy.</param>
/// <param name="fileSystemHelper">A helper class that provides file system services (optional).</param>
/// <exception cref="ArgumentException">Thrown if the path is invalid.</exception>
/// <exception cref="InvalidOperationException">Thrown if there is no Git repository at the specified path.</exception>
public GitLog(string pathToWorkingCopy, FileSystemHelper fileSystemHelper = null)
{
this.fileSystem = fileSystemHelper ?? new FileSystemHelper(); …Run Code Online (Sandbox Code Playgroud) 现在 C# 中是否有任何速记可以减少以下代码:
var testVar1 = checkObject();
if (testVar1 != null)
{
testVar2 = testVar1;
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,如果从 CheckObject() 结果中 testVar1 不为空,则只想分配 testVar2(testVar2 有一个将触发代码的设置器)。试图思考如何使用空合并的东西,但没有真正解决。
添加到此 testVar2 的 setter 上有要触发的代码,因此如果值为 null,则不要将 testVar2 设置为任何内容。
public MyObj testVar2
{
get { return _testVar2; }
set
{
_testVar2 = value;
RunSomeCode();
}
}
Run Code Online (Sandbox Code Playgroud)