类别';s输出在C#中,如何做
这是我的问题:类别';s输出在C#中,如何做,c#,C#,这是我的问题: 我想在调用一个类的实例时从该类输出一个值。 例如,我有这样一个类: class Car { public string name = null; public int id; public int horsepower; public Car(int ID, string Name, int HorsePower) { this.id = ID; this.name = Name; this.
我想在调用一个类的实例时从该类输出一个值。 例如,我有这样一个类:
class Car
{
public string name = null;
public int id;
public int horsepower;
public Car(int ID, string Name, int HorsePower)
{
this.id = ID;
this.name = Name;
this.horsepower = HorsePower;
}
}
class Program
{
static void Main(string[] args)
{
Car car = new Car(1, "aventador lp700-4", 700);
////////////// I want the output will be "aventador lp700-4" /////////////////////
Console.WriteLine(car);
///////////////////////////////
Console.Read();
}
}
我希望当我有这样一个程序时,输出将是“aventador lp700-4”
:
class Car
{
public string name = null;
public int id;
public int horsepower;
public Car(int ID, string Name, int HorsePower)
{
this.id = ID;
this.name = Name;
this.horsepower = HorsePower;
}
}
class Program
{
static void Main(string[] args)
{
Car car = new Car(1, "aventador lp700-4", 700);
////////////// I want the output will be "aventador lp700-4" /////////////////////
Console.WriteLine(car);
///////////////////////////////
Console.Read();
}
}
我发现一些dll库可以做到这一点,但我不知道如何做到。控制台。WriteLine(对象)
希望为传入的对象获取字符串;有几种不同的方法可以做到这一点,但默认情况下(在您没有告诉它更具体的情况下),它只需对参数调用.ToString()
。因此:您需要覆盖Car
上的ToString()
方法,告诉它您想要使用什么来将该类型表示为字符串
:
class Car
{
// ... your existing code
public override string ToString() { return name; }
}
重写car类中的ToString方法
public override string ToString(){
return name;
}
旁注:目前您在类型上有“公共字段”-几乎总是最好使用属性;例如:publicstringname{get;set;}
——它们的工作原理非常相似,但以后会变得更加灵活