rad*_*byx 6 .net c# vb.net visual-studio-2012 visual-studio-2013
在C#中检查一个null的VB.NET对象会产生意外的编译错误:
// Cannot compile:
var basePackage = BasePackage.GetFromID(id); // GetFromID is from VB.NET
if (basePackage != null) // Errormesage: "Cannot implicitly convert 'object' to 'bool'
{
}
Run Code Online (Sandbox Code Playgroud)
Resharper建议修复:
// Can compile
if ((bool) (basePackage != null))
{
linkedGroups = basePackage.GetLinkedGroups();
}
Run Code Online (Sandbox Code Playgroud)
我有一位同事在一年内没有遇到任何问题.我的同事正在使用Visual Studio 2012而我正在使用Visual Studio 2013.它可能是某种设置吗?
为什么basePackage != null
一个object
?
我知道VB.NET有Nothing
C#所在的地方null
.
更新: BasePackage从另一个类继承了这个:我不知道这是否有任何帮助.
Public Shared Operator =([object] As CMSObject, type As System.Type)
Return [object].GetType Is type
End Operator
Public Shared Operator <>([object] As CMSObject, type As System.Type)
Return [object].GetType IsNot type
End Operator
Public Shared Operator =([object] As CMSObject, o As Object)
Return [object].GetType Is o
End Operator
Public Shared Operator <>([object] As CMSObject, o As Object)
Return [object].GetType IsNot o
End Operator
Run Code Online (Sandbox Code Playgroud)
解决方案: 当我退出这两个操作符时,C#再次正常工作.
Public Shared Operator =([object] As CMSObject, type As System.Type)
Return [object].GetType Is type
End Operator
'Public Shared Operator <>([object] As CMSObject, type As System.Type)
' Return [object].GetType IsNot type
'End Operator
Public Shared Operator =([object] As CMSObject, o As Object)
Return [object].GetType Is o
End Operator
'Public Shared Operator <>([object] As CMSObject, o As Object)
' Return [object].GetType IsNot o
'End Operator
Run Code Online (Sandbox Code Playgroud)
最终解决方案在VB.NET中添加了类型.那时不需要C#cast.
Public Shared Operator =([object] As CMSObject, type As System.Type) **As Boolean**
Return [object].GetType Is type
End Operator
Public Shared Operator <>([object] As CMSObject, type As System.Type) **As Boolean**
Return [object].GetType IsNot type
End Operator
Public Shared Operator =([object] As CMSObject, o As Object) **As Boolean**
Return [object].GetType Is o
End Operator
Public Shared Operator <>([object] As CMSObject, o As Object) **As Boolean**
Return [object].GetType IsNot o
End Operator
Run Code Online (Sandbox Code Playgroud)
我拿了你的 vb 样本,将其编译成 dll 并将其反编译为 c# 这就是你们操作员的样子
public static object operator ==(Class1 @object, Type type)
{
return (object) (bool) (@object.GetType() == type ? 1 : 0);
}
public static object operator !=(Class1 @object, Type type)
{
return (object) (bool) (@object.GetType() != type ? 1 : 0);
}
public static object operator ==(Class1 @object, object o)
{
return (object) (bool) (@object.GetType() == o ? 1 : 0);
}
public static object operator !=(Class1 @object, object o)
{
return (object) (bool) (@object.GetType() != o ? 1 : 0);
}
Run Code Online (Sandbox Code Playgroud)
所以,这只是由于奇怪的运算符重载签名造成的。
您评论了“不等于”运算符,现在它似乎可以工作,但是当您编写类似的内容时,您会得到相同的错误
if ( (basePackage == null))
// etc.
Run Code Online (Sandbox Code Playgroud)
正如评论中所建议的,解决方案是将运算符重载签名指定为布尔值。