1
我正在学习VB.NET和C# 我在VB中有以下代码,我在C#中转换。代码有一个Form,一个基类Vehicle和一个派生类Car。在VB中,基类Vehicle作为4个属性声明,只有一行没有设置&,而在C#中,我首先必须声明变量,然后设置&的4个属性获取方法(和很多行)。这是正确的方式,还是有一个像VB一样简单的方法?
VB.NET属性和方法从VB.NET转换为C#
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);
}
}