[英]Cannot convert type bool to int
我丢失了源代码,不得不从DLL反编译,并且在LINQ to SQL DataContext类的代码中收到以下错误。
错误CS0030无法将类型'布尔'转换为'整数'
看起来VS生成的代码出于某种奇怪的原因而使用int而不是bool。 请参阅下面的星号线。 我该怎么做才能解决此投射错误? 本课程使用了一百多次。
public int? OrderBy
{
get
{
return this._OrderBy;
}
set
{
int? nullable = this._OrderBy;
int? nullable1 = value;
**if ((nullable.GetValueOrDefault() != nullable1.GetValueOrDefault() ? 1 : (int)(nullable.HasValue != nullable1.HasValue)) != 0)**
{
this.SendPropertyChanging();
this._OrderBy = value;
this.SendPropertyChanged("OrderBy");
}
}
}
编辑:这个问题的答案是“获得更好的反编译器”。 上面的代码是由Telerik Just Decompile生成的。 ILSpy生成实际上有意义的代码。 在这种情况下:
[Column(Storage = "_OrderBy", DbType = "Int", UpdateCheck = UpdateCheck.Never), DataMember(Order = 6)]
public int? OrderBy
{
get
{
return this._OrderBy;
}
set
{
if (this._OrderBy != value)
{
this.SendPropertyChanging();
this._OrderBy = value;
this.SendPropertyChanged("OrderBy");
}
}
}
这个问题可能应该删除。 建议发表评论。
您可能想要这样:
if ((nullable.GetValueOrDefault() != nullable1.GetValueOrDefault()) || (nullable.HasValue != nullable1.HasValue))
结果应该与您所得到的相同,但可读性更高。
您不能直接将bool
转换为int
:
(int)(nullable.HasValue != nullable1.HasValue) //invalid
但您可以使用Convert.ToInt32
:
Convert.ToInt32(nullable.HasValue != nullable1.HasValue) //valid
因此,您的代码应为:
if ((nullable.GetValueOrDefault() != nullable1.GetValueOrDefault() ? 1 : Convert.ToInt32(nullable.HasValue != nullable1.HasValue)) != 0)
但是,由于运算符“解除”,我认为您只能进行简单的比较。 从C#规范:
对于相等运算符== [和]!=如果操作数类型均为非空值类型且结果类型为bool,则存在运算符的提升形式。 抬起的表格是通过添加一个?来构造的。 每个操作数类型的修饰符。 提升运算符认为两个空值相等,并且一个空值不等于任何非空值。 如果两个操作数都不为空,则提升操作符将取消包装操作数并应用基础操作符以产生布尔结果。
因此,您可以使用:
if (nullable != nullable1)
当然这意味着您可以完全忽略nullable
和nullable1
变量并使用
if (this._OrderBy != value)
我相信这接近于人类会写的内容(而不是反编译器)。
不知道为什么OrderBy是一个int ?,但是别说了...
编辑
另请注意,帖子中的条件运算符为true时返回1,为false时返回布尔。 解决了帖子中的问题(无法将bool转换为int)后,您将收到无法将int转换为bool的错误。
int? _OrderBy;
public int? OrderBy
{
get
{
return _OrderBy;
}
set
{
if ((_OrderBy.GetValueOrDefault() != value.GetValueOrDefault()) || (_OrderBy.HasValue != value.HasValue))
{
SendPropertyChanging();
_OrderBy = value;
SendPropertyChanged("OrderBy");
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.