提问人:Student 提问时间:9/20/2017 最后编辑:ThumperStudent 更新时间:9/20/2017 访问量:240
将类设置为另一个单独类中的属性
Setting a class as a property within another separate class
问:
对于我的项目,我有几个类。我想通过以下方式将其中两个类联系在一起: 这是一个基本的预算应用程序。
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 中的 Car 属性分配 Car 的属性,例如:
budget.CarProperty.Insurance = 500;
我不知道这是否可能,如果不是,或者我正在做一些完全荒谬的事情。 在我的 Manager 类和我的 BLL 类库中,我有一个在分配预算后返回预算的方法。汽车财产保险 = 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)
}
预算。CarProperty.Insurance 只是返回为 0 而不是 500。 同样,我可能遗漏了一些小细节并且对某些事情一无所知,所以请放轻松
答:
0赞
Thumper
9/20/2017
#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);
}
对代码进行了单元测试,它按预期工作。
评论
0赞
Student
9/21/2017
非常感谢,这正是我想做的。关于你所说的,“总的来说,我同意@Plutonix关于班级是自我维持的。我想知道将类作为类中的属性通常不是好的编程。我想确保我的代码是灵活的、可维护的和可测试的,所以这样做通常是不好的,我想确保我将来不会这样做。
0赞
Thumper
9/21/2017
通常,您经常会在另一个类中找到表示为 Properties 的类。在您的示例中,有人可能会争辩说所有预算项目都应该在预算类中。 例如:您可能有一个更通用的 BudgetItem 类,该类具有属性类别、成本等......和 BudgetItem 将表示为 IEnumerable<BudgetItem> BudgetItems {set; get; }
评论