在ac#类中重载vb.net和运算符

我这里有一个非常独特的问题。 我们的业务应用程序是使用c#和vb.net构建的。 我们一直试图接近一个标准,并削减我们的一些核心,已经重复的对象的脂肪。 我们正在变得非常接近,但是当我试图将一个重复的对象合并到c#中时,我们的vb.net代码现在开始抛出错误“运算符’&’未定义为类型’CSType’和’String’,当我尝试执行vb时使用和号(&)的.net字符串连接。有趣的是,如果我在c#中使用带有CSType的’&’(在正确重载之后),我得到了我期望的字符串连接。

以下是我对CSType的基本重载:

public static string operator &(CSType c1, string s2) { return c1.ToString() + s2; } public static string operator &(string s1, CSType c2) { return s1 + c2.ToString(); } 

当我使用CSType和字符串在c#中运行’&’运算符时,我得到了预期的结果,当我尝试在vb.net中执行时,代码将无法编译,从而给出了一个错误:

“运算符’和’未定义类型’CSType’和’字符串’”

CSType也隐式转换为大多数数据类型,所以我认为’&’可能存在一些问题,假设它是一个按位运算符,但我猜想通过给我乱搞执行而不是编译会失败错误。

无论如何,我有点想把这个课放在c ++中,我知道我可以从中得到我需要的东西,但已经不够用2种语言了。

C#中的&运算符是按位AND运算符。 所以当你超载它时

 public static string operator &(CSType c1, string s2) { return c1.ToString() + s2; } public static string operator &(string s1, CSType c2) { return s1 + c2.ToString(); } 

你可以使用And运算符在VB.Net中使用它:

 Dim a = New CSType("Foo") Dim b = "Bar" Dim c = a And b 

但是,要在VB.Net之外重载VB.Net的&运算符(例如C#),您必须创建一个名为op_Concatenate的方法并使用SpecialName属性:

 [SpecialName] public static string op_Concatenate(CSType c1, string s2) { return c1.ToString() + s2; } [SpecialName] public static string op_Concatenate(string s1, CSType c2) { return s1 + c2.ToString(); } 

然后以下代码将起作用:

 Dim a = New CSType("Foo") Dim b = "Bar" Dim c = a & b