我正在学习VB.NET和C#,我在VB中有下面的代码,我用C#转换了这些代码。代码有一个表单、一个基类工具和一个派生类Car。在VB中,基类Vehicle作为4个属性声明,只有一行没有set & get,而在C#中,我首先必须声明变量,然后使用set & get方法(和很多行)声明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 ClassC#
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);
}
}发布于 2017-05-26 12:47:19
您还可以像下面这样直接定义属性
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; } ;
}https://stackoverflow.com/questions/44201899
复制相似问题