标签: null-coalescing-operator

ASP.NET MVC/C# - Null Coalescing Operator,Types

我正在尝试在我的页面上创建分页.用户可以选择每页显示的项目数,然后首选大小将保存为cookie.但是当我尝试在querystring参数和cookie之间进行选择时,发生了错误:

    public ActionResult Index(string keyword, int? page, int? size)
    {
        keyword = keyword ?? "";
        page = page ?? 1;

        //Operator "??" cannot be applied to operands of type "int" and  "int"
        size = size ?? Convert.ToInt32(Request.Cookies.Get("StoriesPageSize").Value) ?? 10; 
Run Code Online (Sandbox Code Playgroud)

是什么导致了这个错误?怎么解决?

c# asp.net-mvc null-coalescing-operator

1
推荐指数
1
解决办法
1044
查看次数

以三元表达式合并评估者是不是很糟糕?(C#)

我环顾四周,没找到一个同等的问题.
这是不好的编码练习吗?我可以很容易地阅读它,但对于阅读代码的人来说它是否太神秘了?

bool? testBool = null;  
string result;  
result = (testBool ?? false ? "Yes" : "No");  
Run Code Online (Sandbox Code Playgroud)

编辑:我向大家道歉,感谢一些可怕的代码!这是一个有效的例子.
我对回复的速度感到有些不知所措.我打算删除这个并且做得对,但已经有4个回复了!

c# ternary-operator null-coalescing-operator

0
推荐指数
1
解决办法
388
查看次数

结合多次合并?

C#中有什么东西可以让你做一些像

string str = nullval1 ?? nullval2 ?? nullval3 ?? "Hi";
Run Code Online (Sandbox Code Playgroud)

它会从左到右选择第一个非空的?

如果这个操作符不这样做,是否有可能用最少的代码提供类似的功能?

c# null-coalescing-operator

0
推荐指数
1
解决办法
72
查看次数

c#null string?

我有以下内容:

string Name = name.First + " "  +  name.Last;
Run Code Online (Sandbox Code Playgroud)

Tom Jones很好.

如果name.First可能为null或name.Last可能为null,我有以下内容:

string SpeakerName = name.First ?? string.Empty + " "  +  name.Last ?? string.Empty;
Run Code Online (Sandbox Code Playgroud)

奇怪的是它只会返回Tom.为什么这个以及如何修复它以if null使其默认为空名字符串为姓或名?

c# operator-precedence null-coalescing-operator

0
推荐指数
2
解决办法
247
查看次数

null合并运算符中的这个额外询问是什么?

我有条件:

if (dr_dados["DAT_SAIDA"] != null)
    {
        txtDataSaida.Text = "";
    }
    else
    {
        txtDataSaida.Text = dr_dados["DAT_SAIDA"].ToString();
    }
Run Code Online (Sandbox Code Playgroud)

我正在使用Jetbrain的ReSharper,它告诉我可以转换成三元操作.

所以,它变成了这样:

txtDataSaida.Text = (dr_dados["DAT_SAIDA"] != null) ? dr_dados["DAT_SAIDA"].ToString() : "";
Run Code Online (Sandbox Code Playgroud)

但后来它告诉我,我可以转换为空合并操作,它给了我这个:

txtDataSaida.Text = dr_dados["DAT_SAIDA"]?.ToString() ?? "";
Run Code Online (Sandbox Code Playgroud)

我有点知道null合并操作的作用,但是有一些不同的东西,我以前没见过的东西,我想知道它是什么.

这个额外的审讯就在这里:

                                         v
txtDataSaida.Text = dr_dados["DAT_SAIDA"]?.ToString() ?? "";
Run Code Online (Sandbox Code Playgroud)

它是什么意思/是什么意思?

c# resharper ternary-operator null-coalescing-operator c#-6.0

0
推荐指数
1
解决办法
53
查看次数

混合类型的Nil合并运算符

是否有任何简便的快速简便方法可以获取非String类型的可选值,并获取String值,如果它是.some(),则为该值的String解释;如果它是.none(),则为默认值下列:

let statusCode = (resp as? HTTPURLResponse)?.statusCode
let statusCodeString: String
if let statusCode = statusCode {
    statusCodeString = "\(statusCode)"
} else {
    statusCodeString = "None"
}
Run Code Online (Sandbox Code Playgroud)

对于一个相对简单的事情来说,它似乎太冗长了,感觉就像我缺少明显的东西。

仅使用nil-coalescing运算符不起作用,因为您必须提供相同类型的默认值。

null default-value null-coalescing-operator optional swift

0
推荐指数
1
解决办法
112
查看次数

等待null合并运算符引发异常

我遇到一些奇怪的行为。

运行这段代码时:

var foo = await actionContext.RequestContext?.Principal?.ToUserTokenAsync() ?? UserToken.UnidentifiedUser;
Run Code Online (Sandbox Code Playgroud)

Principalnull在运行时,我得到一个空引用异常。

为什么它不只是返回-> UserToken.UnidentifiedUser

c# null-coalescing-operator async-await

0
推荐指数
1
解决办法
203
查看次数

C#,这个“if...else...”块是否相当于使用空合并运算符的一行代码

我很好奇这段代码是否:

//value is an object, maybe null, maybe not
if (value == null)
   item.PassageStimuliTitle = "";
else
   item.PassageStimuliTitle = value.ToString().Trim();
Run Code Online (Sandbox Code Playgroud)

相当于这一行:

item.PassageStimuliTitle = (string)(value ?? value.ToString().Trim());
Run Code Online (Sandbox Code Playgroud)

我已经使用 if...else... 很长时间了,但最近在 C# 中遇到了空合并运算符。我用它来防止方法调用中传递的参数出现空异常错误。我认为在上面的示例中使用它是等效的,并将代码从 4 行压缩为 1 行。感谢您的阅读。很想听到反馈。

我希望这两个例子是等效的,但很好奇是否有我遗漏的东西。

c# if-statement null-coalescing-operator

0
推荐指数
1
解决办法
1291
查看次数

C#3.5中'??' - 运算符的奇怪行为

这是一个错误还是我解释'??' - 运算符错了?查看下面的获取属性和评论.

我正在使用C#.NET 3.5

    private List<MyType> _myTypeList;

    private List<MyType> MyTypeList
    {
        get
        {
            //The two code lines below should each behave as the three under, but they don't?
            //The ones uncommented are working, the commented result in my list always returning empty (newly created I suppose).

            //return _myTypeList ?? new List<MyType>();
            //return _myTypeList == null ? new List<MyType>() : _myTypeList;

            if (_myTypeList == null)
                _myTypeList = new List<MyType>();
            return _myTypeList;
        }
    }
Run Code Online (Sandbox Code Playgroud)

编辑:对于那些在新问题时看过这个问题的人,很抱歉,那里的一些错误让每个人都感到困惑.

感谢所有伟大而快速的反馈!我现在明白了我犯的错误.谢谢!

c# null-coalescing-operator .net-3.5

-1
推荐指数
2
解决办法
386
查看次数

为什么将null赋给此变量?

所以我刚刚发现了空合并三元运算符,但我似乎无法弄清楚为什么我的变量仍然在下面的代码行中设置为null.

MenuItem parent = (treeView.SelectedItem ?? treeView.Items[0]) as MenuItem;
Run Code Online (Sandbox Code Playgroud)

该对象treeView有多个项目.

无论是否treeView具有所选项,变量始终为null.

任何帮助将不胜感激,谢谢:)

c# null-coalescing-operator

-3
推荐指数
1
解决办法
73
查看次数

为什么Null Coalesce运算符仍然返回null?

我有这个例程:

    try
    {
        CurrentSessionName = SelectedSession?.Name ?? "No Session Selected";
        CurrentSessionTolerance = SelectedSession?.Tolerance.ToString() ?? "N/A";
        CurrentSessionVerification = SelectedSession?.Verification.Description ?? "N/A";
    }
    catch (Exception ex)
    {
        var whatever = ex.GetType(); // hits here with no provided information
        Console.WriteLine("Null Reference Exception"); // ignores this
        string name = SelectedSession?.Name; // and this
    }
Run Code Online (Sandbox Code Playgroud)

那么为什么NullReferenceException即使SelectedSession不是Null ,它仍会抛出错误?

c# null-coalescing-operator nullreferenceexception

-5
推荐指数
1
解决办法
141
查看次数

如果为null,null条件运算符是否返回false?

我有条件的

if (item?.Value2?.GetType() != typeof(string) && item.get_Value() == 0)

我相信如果item为null,?.操作将返回null,我认为这将解决为false导致条件短路并且一切都会很好(item.get_Value()不会被调用)

但是我不确定,我想也许我需要这样做

if (item?.Value2?.GetType() ?? 0 != typeof(string) && item.get_Value() == 0)

但我认为这可能是矫枉过正,是否可以安全地避免潜在的空引用异常?

c# null-coalescing-operator nullreferenceexception c#-6.0

-5
推荐指数
1
解决办法
1137
查看次数