【问题标题】:Setting a class as a property within another separate class将一个类设置为另一个单独类中的属性
【发布时间】:2018-02-28 20:44:36
【问题描述】:

对于我的项目,我有几个课程。我想通过以下方式将其中两个课程联系在一起: 它是一个基本的预算应用程序。

public class Car
{ 
    public int Insurance { get; set; }
    public int Gas { get; set; }
}

public class Budget
{ 
    public Car CarProperty { get; set; }
    public Budget()
    {
        CarProperty = new Car();
    } 
}

这可能是不可能的,但我想只实例化 Budget 类 像这样

Budget budget = new Budget();

然后我想通过预算中的汽车属性分配汽车的属性,例如:

budget.CarProperty.Insurance = 500;

我不知道这是否可能,如果不是,或者我正在做一些完全荒谬的事情。 在我的 BLL 类库的 Manager 类中,我有一个在分配budget.CarProperty.Insurance = 500;

后返回预算的方法

例如:

public class BudgetManager()
{ 
    public void BudgetCreation()
    { 
        Budget budget = new Budget();
        budget.CarProperty.Insurance = 500;
        return budget;
    } 
}

使用 Nuget

我创建了一个测试方法,它创建了一个新的预算实例

public void TestMethod()
{
    Budget budget = new Budget();
    BudgetManager manager = new BudgetManager();
    budget = manager.BudgetCreation();
    Assert.AreEqual(500, budget.CarProperty.Insurance)
}

budget.CarProperty.Insurance 只是返回 0 而不是 500。 同样,我可能遗漏了一些小细节并且对某些事情一无所知,所以请放轻松

【问题讨论】:

  • 您的代码显示 CarCosts 和 Budget 类。你的汽车课在哪里?
  • 类通常应该更加自给自足。您不必通过它们外部的代码来构建它们。更一般地说,我认为汽车成本只是一个类别而不是另一个类别,否则您可能会有几十个几乎相同的类别
  • 是的,有可能,尽管您收到错误,因为 Budget 类的 CarProperty 尚未实例化,将 public AddResponse() 更改为 public Budget(),这样您就定义了一个构造函数到你的班级。
  • 访问属性的属性是可能的,并不荒谬。你有没有尝试过?是什么让你认为这是不可能的?我猜是什么引发了这个问题。
  • 我编辑了以前的代码以消除一些错误,因为我试图输入问题太快。我试图解释我到底在哪里遇到问题,那是在我的测试课上。当我在 Visual Studio 中查看本地窗口时,它没有识别出我分配了该属性并且基本上显示为零

标签: c# class properties nullreferenceexception


【解决方案1】:

总的来说,我同意@Plutonix 关于类是自我维持的......但是,如果我理解正确,你希望能够做到这一点:

budget.CarProperty.Insurance = 500;

不必这样做,首先:

budget.CarProperty = new Car();

在这种情况下,您可以这样做:

public class Car
{ 
    public int Insurance { get; set; }
    public int Gas { get; set; }
}

public class Budget
{ 
    public Car Car { get; set; }
    public Budget()
    {
        Car = new Car();
    } 
}

public class BudgetManager
{ 
    public static Budget CreateBudget(int insurance)
    { 
        Budget budget = new Budget();
        budget.Car.Insurance = insurance;
        return budget;
    } 
}

因此,当您运行单元测试时,您将获得所需的行为:

[TestMethod]
public void TestMethod1() 
{

    int insurance = 500;
    Budget b = BudgetManager.CreateBudget(insurance);

    Assert.AreEqual(insurance, b.Car.Insurance);
}

对代码进行了单元测试,它按预期工作。

【讨论】:

  • 非常感谢,这正是我想做的。关于你所说的,“总的来说,我同意@Plutonix 关于类是自我维持的。”我想知道将类作为类中的属性通常是否不是好的编程。我想确保我的代码灵活、可维护和可测试,所以这样做通常很糟糕,我想确保我以后不会这样做。
  • 一般来说,您会经常发现在另一个类中表示为属性的类。在您的示例中,有人可能会争辩说所有预算项目都应该在预算类中。例如:您可能有一个更通用的 BudgetItem 类,它具有属性类别、成本等......并且 BudgetItem 将表示为 IEnumerable BudgetItems {set;得到; }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-12-04
  • 1970-01-01
  • 2011-11-05
  • 1970-01-01
  • 1970-01-01
  • 2020-09-09
  • 2013-09-04
相关资源
最近更新 更多