gpt4 book ai didi

c# - 从 VB.NET 到 C# 的属性和方法覆盖转换

转载 作者:太空宇宙 更新时间:2023-11-03 21:02:23 24 4
gpt4 key购买 nike

我正在学习 VB.NET 和 C#我在 C# 中转换的 VB 中有以下代码。该代码有一个 Form、一个基类 Vehicle 和一个派生类 Car。在 VB 中,基类 Vehicle 作为 4 个属性声明,只有一行没有设置和获取,而在 C# 中,我首先必须声明变量,然后是 4 个属性与设置和获取方法(和很多行)。这是正确的方法还是像 VB 中的简单方法?

VB.NET

Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim myCar As New Car()
myCar.Make = "Ferrari"
myCar.Model = "Testa rossa"
myCar.Year = 1999
myCar.Color = "Red"

PrintVehicleDetails(myCar)
End Sub

Public Sub PrintVehicleDetails(ByVal _vehicle As Vehicle)
Console.WriteLine("Here is the car's details: {0}", _vehicle.FormatMe())
End Sub
End Class


Public MustInherit Class Vehicle
Public Property Make As String

Public Property Model As String

Public Property Year As Integer

Public Property Color As String

Public MustOverride Function FormatMe() As String

End Class


Public Class Car
Inherits Vehicle
Public Overrides Function FormatMe() As String
Return String.Format("{0} - {1} - {2} - {3}",
Me.Make, Me.Model, Me.Year, Me.Color)
End Function
End Class

C#

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
Car myCar = new Car();
myCar.make = "Ferrari";
myCar.model = "Testa rossa";
myCar.year = 1999;
myCar.color = "Red";

PrintVehicleDetails(myCar);
}

private void PrintVehicleDetails(Vehicle _vehicle)
{
Console.WriteLine("Here is the car's details: {0}", _vehicle.FormatMe());
}
}

abstract class Vehicle
{
string Make = "";
string Model = "";
int Year = 0;
string Color ="";

public string make
{
get
{ return Make; }

set
{ Make = value; }
}

public string model
{
get
{ return Model; }

set
{ Model = value; }
}

public int year
{
get
{ return Year; }

set
{ Year = value; }
}

public string color
{
get
{ return Color; }

set
{ Color = value; }
}

abstract public string FormatMe();
}

class Car : Vehicle
{
public override string FormatMe()
{
return String.Format("{0} - {1} - {2} - {3}",
this.make, this.model, this.year, this.color);
}
}

最佳答案

你也可以像下面这样直接定义属性

abstract class Vehicle
{
public string Make { get; set; } = string.Empty;

public string Model{ get; set; } = string.Empty;

public int Year{ get; set; } = 0;

public string Color { get; set; } ;
}

关于c# - 从 VB.NET 到 C# 的属性和方法覆盖转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44201899/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com