如何解决打印一些数据
我一直在尝试打印有关设备是mobile
还是immobile
的信息,但是由于某种原因,它没有显示任何输出。
public class Equipment
{
public string name;
public string description;
public string type;
public int distance_moved = 0;
public int wheels = 0;
public int weight = 0;
public int maintenance_cost;
public Equipment(string n,string d,string t,int w,int wt)
{
n = name;
d = description;
t = type;
w = wheels;
wt = weight;
}
public void Move_By(int d)
{
distance_moved = distance_moved + d;
if (this.type == "Mobile")
{
maintenance_cost = wheels * distance_moved;
}
else maintenance_cost = weight * distance_moved;
}
}
class Program
{
static void Main(string[] args)
{
var Equipment_list = new List<Equipment>()
{
new Equipment("Bulldozer","Light Vehicle","Mobile",4,0),new Equipment("Box","Huge Box","ImMobile",10),new Equipment("Drill Machine","Light Machine",20),new Equipment("Truck","Heavy Vehicle",0)
};
var Mobile_Equipment = from Mobile in Equipment_list
where Mobile.type == "Mobile"
orderby Mobile.name
select Mobile;
foreach (var Mobile in Mobile_Equipment)
{
Console.WriteLine("{0} is a Mobile Equipment",Mobile.name);
}
Console.ReadKey();
}
}
解决方法
您的Equipment
构造函数正在向后进行所有分配。您正在将默认的类成员值分配给方法参数。应该是这样的:
public Equipment(string n,string d,string t,int w,int wt)
{
name = n;
description = d;
type = t;
wheels = w;
weight = wt;
}
,
Equipment
的构造函数中的分配顺序错误。使用公共字段也不是一个好主意。字段是实现细节,即使它们是公共的。
该类应如下所示:
public class Equipment
{
public string Name {get;set;}
public string Description {get;set;}
public string Type {get;set;}
public int Distance_moved {get;set;}= 0;
public int Wheels {get;set;} =0;
public int Weight {get;set;} =0;
public int Maintenance_cost {get;set;} =0;
public Equipment(string name,string description,string type,int wheels,int weight)
{
Name = name;
Description = description;
Type = type;
Wheels = wheels;
Weight = weight;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。