java - 将 Java 构造函数从抽象类和 super 关键字转换为 C# 时出错?

标签 java c# constructor

我有两个 Java 类,我正在尝试将其转换为 C#。一个是名为 RemoteButton 的抽象类,另一个是从它派生的名为 TVRemoteMute 的类。我能够转换抽象 RemoteButton 类中的大多数成员。一个成员是抽象的buttonNinePressed(),在TVRemoteMute中实现,另一个是在基类中实现的虚拟成员buttonFivePressed()。我的问题是 TVRemoteMute 类的构造函数。它突出显示了两个单词,构造函数名称和方法内的单词 super。构造函数名称错误显示:“没有给出与‘RemoteButton.RemoteButton(EntertainmentDevice)’所需的形式参数‘newDevice’相对应的参数。‘super’关键字错误表明该名称在当前上下文中不存在。我如何从 Java 到 C# 实现此构造函数,以便我的类可以处理该构造函数?

public abstract class RemoteButton
{
    private EntertainmentDevice theDevice;

    public RemoteButton(EntertainmentDevice newDevice)
    {
        theDevice = newDevice;
    }

    public virtual void buttonFivePressed()
    {
        theDevice.buttonFivePressed();
    }

    public abstract void buttonNinePressed();

 }

public class TVRemoteMute : RemoteButton
{
    public TVRemoteMute(EntertainmentDevice newDevice)
    {
        super(newDevice);
    }

    public override void buttonNinePressed()
    {

        Console.WriteLine("TV was Muted");

    }
}

最佳答案

C# 中不使用关键字 super;调用基类的构造函数与 Java 中不同。

TVRemoteMute 中的构造函数更改为:

public TVRemoteMute(EntertainmentDevice newDevice) : base(newDevice)
{

}

实际上,如果您不在构造函数主体中执行任何其他操作,我更喜欢这样做,但这并不重要:

public TVRemoteMute(EntertainmentDevice newDevice) : base(newDevice) { }

编译后,另一个错误应该会自行修复。

关于java - 将 Java 构造函数从抽象类和 super 关键字转换为 C# 时出错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42001874/

相关文章:

c# - 运算符 == 不能应用于 C# 中的泛型类型吗?

c# - 向面板添加垂直滚动条

c++ - 隐式构造函数调用

c# - 如何在 RestSharp 中反序列化 JSON?

java - 在java游戏中打开问题

java - 将字节流转换为对象

java - 使用递归类定义创建第一个对象

使用头文件时的 C++ 显式父类(super class)构造函数问题

c# - 构造函数可访问性 C# 编译器错误 CS0122 与 CS1729

解析大型 xml 文件时发生 Java 堆空间错误