使用 Nullable进行条件运算符赋值 类型?

发布于 2024-07-04 04:00:41 字数 609 浏览 9 评论 0原文

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

我经常发现自己想做这样的事情(EmployeeNumber 是一个 Nullable 因为它是 LINQ-to-SQL dbml 对象上的一个属性,其中列允许 NULL值)。 不幸的是,编译器认为

'null' 和 'int' 之间没有隐式转换

即使这两种类型在对可为 null int 的赋值操作中都是有效的。

据我所知,使用 null 合并运算符不是一个选项,因为如果 .Text 字符串不为 null,则需要在该字符串上进行内联转换。

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

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

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

I often find myself wanting to do things like this (EmployeeNumber is 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.

Using the 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.

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...

Does anyone know a more elegant solution?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

三生路 2024-07-11 04:00:41

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

如果您确实想以这种方式使用它,则必须自己将其中一个值强制转换为 Nullable,以便 C# 可以解析该类型:

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

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

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 null and an Int32, and the type can not be determined (there are real reasons it can't just assume 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:

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

or

EmployeeNumber =
    string.IsNullOrEmpty(employeeNumberTextBox.Text)
    ? null
    : (int?)Convert.ToInt32(employeeNumberTextBox.Text),
格子衫的從容 2024-07-11 04:00:41

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

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);
    }
}

然后

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

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);
马蹄踏│碎落叶 2024-07-11 04:00:41

C# 9.0,这最终将成为可能:

目标输入?? 和?:

有时是有条件的? 和 ?: 表达式在分支之间没有明显的共享类型。 这种情况今天会失败,但如果存在两个分支都转换为的目标类型,C# 9.0 将允许它们:

人=学生??   顾客;   // 共享基类型 
  整数?   结果 = b ?   0:空;   // 可空值类型 
  

这意味着问题中的代码块也将编译而不会出现错误。

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

As of C# 9.0, this will finally be possible:

Target typed ?? and ?:

Sometimes conditional ?? and ?: expressions don’t have an obvious shared type between the branches. Such cases fail today, but C# 9.0 will allow them if there’s a target type that both branches convert to:

Person person = student ?? customer; // Shared base type
int? result = b ? 0 : null; // nullable value type

That means the code block in the question will also compile without errors.

EmployeeNumber =
string.IsNullOrEmpty(employeeNumberTextBox.Text)
    ? null
    : Convert.ToInt32(employeeNumberTextBox.Text),
眼眸 2024-07-11 04:00:41
//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;

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

//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 int and having value greater than 0) in varibale X1. I had to use (int?) on Posid.Value to get the conditional operator not throwing any compilation error.
Just a FYI GetHolidayCount is a WCF method that could give null or any number.
Hope that helps

南冥有猫 2024-07-11 04:00:41

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

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

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

While Alex provides the correct and proximal answer to your question, I prefer to use 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 1b they will be presented with an error page with the unhandled exception caused in Convert.ToInt32(string).

许你一世情深 2024-07-11 04:00:41

您可以转换 Convert 的输出:

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

You can cast the output of Convert:

EmployeeNumber = string.IsNullOrEmpty(employeeNumberTextBox.Text)
   ? null
   : (int?)Convert.ToInt32(employeeNumberTextBox.Text)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文