我刚刚遇到一个奇怪的错误:
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>.
我疯了吗?
EmployeeNumber =
string.IsNullOrEmpty(employeeNumberTextBox.Text)
? null
: Convert.ToInt32(employeeNumberTextBox.Text),
Run Code Online (Sandbox Code Playgroud)
我经常发现自己想要做这样的事情(EmployeeNumber是Nullable<int>因为它是在LINQ到SQL的DBML对象,其中列允许NULL值的属性).不幸的是,编译器认为"'null'和'int'之间没有隐式转换",即使这两种类型在对自己的可空int的赋值操作中都是有效的.
由于内联转换需要在.Text字符串上发生(如果它不为空),因此Null合并运算符不是我能看到的选项.
据我所知,唯一的方法是使用if语句和/或分两步进行分配.在这种特殊情况下,我发现非常令人沮丧,因为我想使用对象初始化器语法,这个赋值将在初始化块中...
谁知道更优雅的解决方案?
我正在尝试使用?:运算符来为可分配的布尔变量赋值.
这个原始代码工作正常
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) 我有一个类和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)