【问题标题】:C# - Declaration of class variablesC# - 类变量的声明
【发布时间】:2018-05-22 01:42:24
【问题描述】:

如何创建一个新的波音737 实例并稍后在程序中使用它。例如,我希望能够创建 5 架波音,我是否必须像这样定义它们

Boeing737 boeing1 =  new Boeing737(name: "Boeing737" + Console.ReadLine(),fuel: int.Parse(Console.ReadLine()) , tons: 0);

Boeing737 boeing2 =  new Boeing737(name: "Boeing737" + Console.ReadLine(),fuel: int.Parse(Console.ReadLine()) , tons: 0);

等等…… 还是有更简单的方法? 其他问题,例如,我可以将 boeing1 的所有属性分配给什么?

这是我当前的代码:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Insert the type of boeing that u are using");
        Boeing737 boeing = new Boeing737(name: "Boeing737" + Console.ReadLine(),fuel: int.Parse(Console.ReadLine()) , tons: 0);
        Console.WriteLine("{0} has {1} tons of fuel and weights {2}", boeing.Name, boeing.Fuel, boeing.Tons);
        Console.ReadKey();

    }
}

public class Planes
{
    public Planes(string name, int fuel, int tons)
    {
        Name = name;
        Fuel = fuel;
        Tons = tons;
    }
    public int Tons;
    public int Fuel;
    public string Name { private set; get; }
}
class Boeing737 : Planes
{
    public Boeing737(string name, int fuel, int tons) : base(name, fuel, tons)
    {
        Tons = 700;
    }
}

}

【问题讨论】:

  • 了解数组和循环..
  • 我还建议您不要在构造函数中调用Console.ReadLine()(更不用说两次了)。单独调用,捕获输出,并在构造函数中使用 that
  • 我建议你谷歌并阅读C# Basics Tutorial 关注变量、类、封装、属性
  • 我建议您也研究一下正确的语法。讨厌成为那种人,但即使是在学校作业中,他们也可能会因为 boeing that u are using 而敲你
  • 我在这里没有得到反对票,这是一个完全有效的问题,OP 付出了一些努力,有些问题也许可以更好地调查,但绝对没有不好(即使感觉这是一个功课问题,它也显示了 OP 所做的一些努力)

标签: c# class variables constructor


【解决方案1】:

使用数组初始化:

var boeings = new []
  {
    new Boeing737("name", 123, 1000),
    new Boeing737("name", 123, 1000),
    new Boeing737("name", 123, 1000),
    new Boeing737("name", 123, 1000),
  };

【讨论】:

  • 谢谢。如何按 .Fuel 对它们进行排序?
  • 使用 linq 非常简单 var boeings = new [] { new Boeing737("name", 123, 1000), new Boeing737("name", 123, 1000), new Boeing737("name", 123, 1000), new Boeing737("name", 123, 1000), }.OrderBy(boeing => boeing.Fuel); 如果您想要不同于 IEnumerable 的东西,请使用额外的 .ToArray() 或 .ToList()
  • 非常感谢,现在我只需要知道一件事。我怎样才能叫第三个排序的波音公司的名字?
  • 您的意思是访问集合中第三个元素的名称? string boeingName = boeings[2].Name; 只需确保在使用 OrderBy 后使用了 .ToArray() 或 ToList()
【解决方案2】:

我会创建一个波音737 的列表,我不会从控制台直接输入。

List<Boeing737> boeingList = new List<Boeing737>();
boeingList.add(new Boeing737() { param=value...});

稍后您可以通过索引、名称、循环访问它们等来访问它们。

我也会研究 Linq

【讨论】:

    【解决方案3】:

    好吧,让我们从改进你的代码开始吧:

    // the class represents a single object, give it a
    // singular name
    public class Plane
    {
        // get before set, it's not mandatory but give yourself
        // some basic coding rules to improve code maintainability
        // and readability
        // avoid public members, implementing properties is always
        // a good choice for future extensions and manipulations
        public int Fuel { get; private set; }
        public int Tons { get; private set; }
        public string Name { get; private set; }
    
        public Plane(string name, int fuel, int tons)
        {
            Name = name;
            Fuel = fuel;
            Tons = tons;
        }
    }
    
    // if your inheritance stops here, you could set a
    // sealed attribute
    public sealed class Boeing737 : Plane
    {
        // no need to set the property twice, you are already
        // calling the base constructor, pass him the fixed
        // tons value of 700...
        public Boeing737(string name, int fuel) : base(name, fuel, 700)
        {
        }
    }
    

    现在,关于实例化,选择通用的List&lt;T&gt; 类型,它非常易于管理,并且会在您添加更多对象时自行扩展:

    List<Boeing737> boeings = new List<Boeing737>
    {
        new Boeing737("A", 5),
        new Boeing737("B", 5),
        new Boeing737("C", 5),
        new Boeing737("D", 5)
    };
    

    如果你想创建一个可以包含不同类型飞机的List,坚持上层类型:

    List<Plane> planes = new List<Plane>
    {
        new Boeing737("A", 5),
        new Boeing737("B", 5),
        new Boeing737("C", 5),
        new Boeing737("D", 5),
        new AirplaneX("D", 10, 350)
    };
    

    List 也可以与 LINQ 一起使用,以方便其操作和过滤(更多信息 here)。例如,按重量排序:

    var planesSortedTons = planes.OrderBy(x => x.Tons).ToList();
    

    只选择带有Fuel &gt; 10的平面:

    var planesFuel10 = planes.Where(x => x.Fuel > 10).ToList();
    

    附带说明,如果您想通过控制台输入填充大量数据,您需要构建一个无限循环(例如while (true))并通过添加来填充列表:

    static void Main(string[] args)
    {
        List<Boeing737> boeings = new List<Boeing737>();
    
        String input;
    
        while (true)
        {
            Consol.WriteLine("Enter name:");
            input = Console.ReadLine();
    
            if (input.ToLowerInvariant() == "stop")
                break;
    
            String name = input.Trim();
    
            Consol.WriteLine("Enter fuel:");
            input = Console.ReadLine();
    
            if (input.ToLowerInvariant() == "stop")
                break;
    
            Int32 fuel;
    
            try
            {
                fuel = Int32.Parse(input.Trim());
            }
            catch
            {
                Console.WriteLine("Wrong input, stopping!");
                break;
            }
    
            boeings.Add(new Boeing737(name, fuel));
        }
    }
    

    【讨论】:

      【解决方案4】:

      如何使用 C# 数组。

      命名空间 ConsoleApps_examples { 课堂节目 { 静态无效主要(字符串 [] 参数) { //Console.WriteLine("插入您正在使用的波音机型");

              //string sname = Console.ReadLine();
              //int ifuel = int.Parse(Console.ReadLine());
      
              Console.WriteLine(" here are 5 different type of boeing:");
      
              string sname = "";
              int ifuel = 0;
      
              int i;
              int[] fuellist = new int[5] { 99, 98, 92, 97, 95 };
              var nameslist = new string[5]  { "XXA1", "XXA2", "XXA3","XXA4","XXA5"};
      
              //var arr3 = new string[] { "one", "two", "three" };
      
              for (i = 0; i < 5; i++)
              {
                  ifuel = fuellist[i];
                  sname = nameslist[i];
                  Boeing737 boeing = new Boeing737(name: "Boeing737" + sname, fuel: ifuel, tons: 0);
                  Console.WriteLine("{0} has {1} tons of fuel and weights {2}", boeing.Name, boeing.Fuel, boeing.Tons);
      
              }
      
              //Boeing737 boeing = new Boeing737(name: "Boeing737" + sname, fuel: ifuel, tons: 0);
              Console.ReadKey();
      
          }    
      
      
      }
      
      
      public class Planes
      {
          public Planes(string name, int fuel, int tons)
          {
              Name = name;
              Fuel = fuel;
              Tons = tons;
          }
          public int Tons;
          public int Fuel;
          public string Name { private set; get; }
      }
      class Boeing737 : Planes
      {
          public Boeing737(string name, int fuel, int tons) : base(name, fuel, tons)
          {
              Tons = 700;
          }
      }
      

      }

      这是输出: List of 5 types of Boeing planes:

      【讨论】:

        猜你喜欢
        • 2022-06-17
        • 1970-01-01
        • 1970-01-01
        • 2011-09-15
        • 1970-01-01
        • 1970-01-01
        • 2010-12-22
        • 2016-12-15
        • 1970-01-01
        相关资源
        最近更新 更多