在 C# 中检查 null 的 VB.NET 对象会产生意外的编译错误

Checking in C# a VB.NET object for null gives unexpected compile error

在 C# 中检查一个 VB.NET 对象的 null 给出了意外的编译错误:

// Cannot compile:
var basePackage = BasePackage.GetFromID(id); // GetFromID is from VB.NET
if (basePackage != null) // Errormesage: "Cannot implicitly convert 'object' to 'bool'
{
}

Resharper 建议的修复:

// Can compile
if ((bool) (basePackage != null))
{
    linkedGroups = basePackage.GetLinkedGroups();
}

我有一位同事在一年内完成了这项工作,没有任何问题。我的同事使用的是 Visual Studio 2012,我使用的是 Visual Studio 2013。 会不会是某种设置?

为什么 basePackage != nullobject

我知道 VB.NET 有 Nothing 而 C# 有 null.

更新: BasePackage 从另一个 class 继承了这个: 我不知道这是否有任何帮助。

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

解决方案: 当我对这两个运算符进行注释时,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

最终解决方案 在 VB.NET 中添加了类型。那时不需要 C# 转换。

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

我拿了你的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);
}

所以,这只是由于奇怪的运算符重载签名。

你评论了 "Not Equal" 个运算符,现在它似乎可以工作,但是当你写类似

的东西时你会得到同样的错误
if ( (basePackage == null))
// etc.

如评论中所建议的那样,解决方案是将您的运算符重载签名指定为布尔值。