C# Nullable<value> 类型的条件运算符赋值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/75746/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 11:13:12  来源:igfitidea点击:

Conditional operator assignment with Nullable<value> types?

提问by Grank

EmployeeNumber =
string.IsNullOrEmpty(employeeNumberTextBox.Text)
    ? null
    : Convert.ToInt32(employeeNumberTextBox.Text),

I often find myself wanting to do things like this (EmployeeNumberis a Nullable<int>as it's a property on a LINQ-to-SQL dbml object where the column allows NULL values). Unfortunately, the compiler feels that "There is no implicit conversion between 'null' and 'int'", even though both types would be valid in an assignment operation to a nullable int on their own.

我经常发现自己想做这样的事情 ( EmployeeNumberis aNullable<int>因为它是 LINQ-to-SQL dbml 对象上的一个属性,其中该列允许 NULL 值)。不幸的是,编译器认为“'null' 和'int' 之间没有隐式转换”,即使这两种类型在对可空 int 的赋值操作中都是有效的。

Null coalescing operator is not an option as far as I can see because of the inline conversion that needs to happen on the .Text string if it's not null.

就我所见,空合并运算符不是一个选项,因为如果 .Text 字符串不为空,则需要在 .Text 字符串上进行内联转换。

As far as I know the only way to do this is to use an if statement and/or assign it in two steps. In this particular case I find that very frustrating because I wanted to use the object initializer syntax and this assignment would be in the initialization block...

据我所知,唯一的方法是使用 if 语句和/或分两步分配它。在这种特殊情况下,我发现这非常令人沮丧,因为我想使用对象初始值设定项语法并且此分配将在初始化块中...

Anyone know a more elegant solution?

有人知道更优雅的解决方案吗?

采纳答案by Alex Lyman

The problem occurs because the conditional operator doesn't look at how the value is used (assigned in this case) to determine the type of the expression -- just the true/false values. In this case, you have a nulland an Int32, and the type can not be determined (there are real reasons it can't just assume Nullable<Int32>).

出现问题是因为条件运算符不查看如何使用值(在这种情况下分配)来确定表达式的类型——只是真/假值。在这种情况下,您有一个null和一个Int32,并且无法确定类型(有真正的原因它不能假设Nullable<Int32>)。

If you really want to use it in this way, you must cast one of the values to Nullable<Int32>yourself, so C# can resolve the type:

如果你真的想以这种方式使用它,你必须自己将其中一个值强制转换Nullable<Int32>,以便 C# 可以解析类型:

EmployeeNumber =
    string.IsNullOrEmpty(employeeNumberTextBox.Text)
    ? (int?)null
    : Convert.ToInt32(employeeNumberTextBox.Text),

or

或者

EmployeeNumber =
    string.IsNullOrEmpty(employeeNumberTextBox.Text)
    ? null
    : (int?)Convert.ToInt32(employeeNumberTextBox.Text),

回答by Abe Heidebrecht

You can cast the output of Convert:

您可以转换 Convert 的输出:

EmployeeNumber = string.IsNullOrEmpty(employeeNumberTextBox.Text)
   ? null
   : (int?)Convert.ToInt32(employeeNumberTextBox.Text)

回答by NerdFury

I think a utility method could help make this cleaner.

我认为实用方法可以帮助使这个更干净。

public static class Convert
{
    public static T? To<T>(string value, Converter<string, T> converter) where T: struct
    {
        return string.IsNullOrEmpty(value) ? null : (T?)converter(value);
    }
}

then

然后

EmployeeNumber = Convert.To<int>(employeeNumberTextBox.Text, Int32.Parse);

回答by user13493

While Alex provides the correct and proximal answer to your question, I prefer to use TryParse:

虽然亚历克斯为您的问题提供了正确且最接近的答案,但我更喜欢使用TryParse

int value;
int? EmployeeNumber = int.TryParse(employeeNumberTextBox.Text, out value)
    ? (int?)value
    : null;

It's safer and takes care of cases of invalid input as well as your empty string scenario. Otherwise if the user inputs something like 1bthey will be presented with an error page with the unhandled exception caused in Convert.ToInt32(string).

它更安全并处理无效输入的情况以及您的空字符串情况。否则,如果用户输入类似的内容,1b他们将看到一个错误页面,其中包含Convert.ToInt32(string).

回答by Sandeep

//Some operation to populate Posid.I am not interested in zero or null
int? Posid = SvcClient.GetHolidayCount(xDateFrom.Value.Date,xDateTo.Value.Date).Response;
var x1 = (Posid.HasValue && Posid.Value > 0) ? (int?)Posid.Value : null;

EDIT: Brief explanation of above, I was trying to get the value of Posid(if its nonnull intand having value greater than 0) in varibale X1. I had to use (int?)on Posid.Valueto get the conditional operator not throwing any compilation error. Just a FYI GetHolidayCountis a WCFmethod that could give nullor any number. Hope that helps

编辑:上面的简要说明,我试图在 varibale 中获取Posid(如果其非空int且值大于 0)的值X1。我不得不使用(int?)onPosid.Value来让条件运算符不抛出任何编译错误。仅供参考GetHolidayCount是一种WCF可以给出null任何数字的方法。希望有帮助