c# - 在 c# 类中重载 vb.net & 运算符

标签 c# .net 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();
}

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

“运算符‘&’没有为‘CSType’和‘String’类型定义”

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

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

最佳答案

C# 中的& 运算符是按位与运算符。所以当你重载它的时候

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

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

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

但是,要在 VB.Net 之外(例如 C#)重载 VB.Net 的 & 运算符,您必须创建一个名为 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

关于c# - 在 c# 类中重载 vb.net & 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24174318/

相关文章:

c# - 选择排序算法排序错误

c# - FileHelperEngine 构造函数 - InvalidcastException

java - 如何将数据集值传递给 dotnet Web 服务?

c# - 代码签名证书

c# - .NET 中的事件签名 - 使用强类型 'Sender' 吗?

c# - 如何从现有的创建 IServiceCollection?

c# - 如何使用 xssfworkbook npoi 设置字体中的 RGB 颜色

vb.net - 如何写入/读取 "settings"文本文件

c# - 如何在知道方向、角度和距离的情况下找到位置?

.net - 设置用户/角色管理系统 - Multi-Tenancy