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);
}
}