将类设置为另一个单独类中的属性

Setting a class as a property within another separate class

提问人:Student 提问时间:9/20/2017 最后编辑:ThumperStudent 更新时间:9/20/2017 访问量:240

问:

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

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。 同样,我可能遗漏了一些小细节并且对某些事情一无所知,所以请放轻松

C# 属性 NullReferenceException

评论

0赞 lowleetak 9/20/2017
您的代码显示 CarCosts 和 Budget 类。你的汽车类在哪里?
0赞 Ňɏssa Pøngjǣrdenlarp 9/20/2017
一般来说,课程应该更加自给自足。您不必通过它们外部的代码来构建它们。更一般地说,我认为汽车成本只是一个类别而不是另一个类别,否则您可能会有几十个几乎相同的类别
0赞 4D1C70 9/20/2017
是的,这是可能的,尽管您收到错误是因为 Budget 类的 CarProperty 尚未实例化,但将 public AddResponse() 更改为 public Budget(),这样您就可以为类定义构造函数。
0赞 Jason Boyd 9/20/2017
访问属性的属性是可能的,而不是荒谬的。你试过吗?是什么让你认为这是不可能的?促使这个问题的原因是我想我得到了什么。
0赞 Student 9/20/2017
我编辑了我以前的代码以消除一些错误,因为我试图太快地输入问题。我试图解释我到底在哪里遇到了问题,这在我的测试课上。它无法识别我分配了属性,当我在 Visual Studio 中查看局部变量窗口时,基本上显示零

答:

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; }