【问题标题】:C# Object variable not being returned correctlyC# 对象变量未正确返回
【发布时间】:2017-10-24 05:01:03
【问题描述】:

我有一个简单的Machine 对象列表,称为loadedMachines。我向其中添加了 2 个新的 Machine 对象,第二个参数是 machineName 属性。

loadedMachines.Add(new Machine("0", "My cool Yaris", "Toyota"));
loadedMachines.Add(new Machine("1", "My sporty car", "Ferrari"));

foreach (Machine m in loadedMachines)
   {
      Console.WriteLine("Machine being added is: " + m.machineName);
   }

由于某些原因,我的 foreach 循环输出“正在添加的机器是:”并且m.machineName 似乎没有与我的机器对象链接。

这是什么原因?这是我的类定义:

public class Machine
{
    public Machine() { }

    public string Id { get; set; }
    public string machineName { set; get; }
    public string machineType { set; get; }
    public string category { set; get; }
    public string make { set; get; }
    public string modelNumber { set; get; }
    public string information { set; get; }
    public string ownersManualLocation { set; get; }
    public string safetyChecklistSchedule { set; get; }
    public string maintenanceService { set; get; }
    public DateTime registrationExpiry { set; get; }

    public Machine(string id, string machineName, string machineType)
    {
    }
}

【问题讨论】:

  • 你的构造函数不会对你给它的参数做任何事情,因此machineName永远不会被设置为一个值。
  • 哇,我很傻。我需要this.machineName = machineName 谢谢斯宾塞
  • 为什么这被否决了?

标签: c# list oop object


【解决方案1】:

在您的构造函数中,您需要从输入参数中分配属性,如下所示:

public Machine(string id, string machineName, string machineType)
{
    Id = id;
    this.machineName = machineName;
    this.machineType = machineType;
}

附带说明,您通常希望为参数使用与属性不同的名称。 Microsoft 建议的命名标准使用大写的属性名称,因此您将使用 public string MachineName { set; get; } 而不是 public string machineName { set; get; }

如果这样做,构造函数就不需要在属性前面加上this

【讨论】:

  • 谢谢约翰,在盯着屏幕好几个小时后,你是正确的,愚蠢的错误!
【解决方案2】:

你也可以使用属性初始化器而不是构造器。像这样的:

loadedMachines.Add(new Machine() {Id = "0", machineName = "My cool Yaris", machineType = "Toyota"});

这种语法在使用动态构造的对象(如实体)时很常见,因为许多框架不支持在动态创建时调用带参数的构造函数。

【讨论】:

    猜你喜欢
    • 2018-09-19
    • 1970-01-01
    • 2013-10-26
    • 1970-01-01
    • 2011-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多