相关疑难解决方法(0)

可空类型和三元运算符:为什么是`?10:null`禁止?

我刚刚遇到一个奇怪的错误:

private bool GetBoolValue()
{
    //Do some logic and return true or false
}
Run Code Online (Sandbox Code Playgroud)

然后,在另一种方法中,这样的事情:

int? x = GetBoolValue() ? 10 : null;
Run Code Online (Sandbox Code Playgroud)

很简单,如果方法返回true,则为Nullable intx 赋值10 .否则,将null赋给nullable int.但是,编译器抱怨:

错误1无法确定条件表达式的类型,因为int和之间没有隐式转换<null>.

我疯了吗?

.net c# nullable conditional-operator

242
推荐指数
6
解决办法
7万
查看次数

使用Nullable <value>类型的条件运算符赋值?

EmployeeNumber =
string.IsNullOrEmpty(employeeNumberTextBox.Text)
    ? null
    : Convert.ToInt32(employeeNumberTextBox.Text),
Run Code Online (Sandbox Code Playgroud)

我经常发现自己想要做这样的事情(EmployeeNumberNullable<int>因为它是在LINQ到SQL的DBML对象,其中列允许NULL值的属性).不幸的是,编译器认为"'null'和'int'之间没有隐式转换",即使这两种类型在对自己的可空int的赋值操作中都是有效的.

由于内联转换需要在.Text字符串上发生(如果它不为空),因此Null合并运算符不是我能看到的选项.

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

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

c# nullable conditional-operator

58
推荐指数
3
解决办法
2万
查看次数

c#为可空布尔值赋值

我正在尝试使用?:运算符来为可分配的布尔变量赋值.

这个原始代码工作正常

bool? result;
var condition = 3;

if (condition == 1)
    result = true;
else if (condition == 2)
     result = false;
else result = null;
Run Code Online (Sandbox Code Playgroud)

我更改代码后,它遇到错误,我在搜索互联网后修复它

// before (error occur)
result = condition == 1 ? true : (condition == 2 ? false : null);

// after (fixed error)
result = condition == 1 ? true : (condition == 2 ? false : (bool?)null); 
// *or
result = condition == 1 ? true : (condition == …
Run Code Online (Sandbox Code Playgroud)

c# nullable

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

导致此"无隐式转换"错误的原因是什么?

我有一个类和2个子类:

public class User
{
    public string eRaiderUsername { get; set; }
    public int AllowedSpaces { get; set; }
    public ContactInformation ContactInformation { get; set; }
    public Ethnicity Ethnicity { get; set; }
    public Classification Classification { get; set; }
    public Living Living { get; set; }
}

public class Student : User
{
    public Student()
    {
        AllowedSpaces = AppSettings.AllowedStudentSpaces;
    }
}

public class OrganizationRepresentative : User
{
    public Organization Organization { get; set; }

    public OrganizationRepresentative()
    {
        AllowedSpaces = …
Run Code Online (Sandbox Code Playgroud)

c#

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

标签 统计

c# ×4

nullable ×3

conditional-operator ×2

.net ×1