好吧,标题是这样说的,但我会更具体地说明我的情况,并解释我的问题。我有以下课程:
class Attribute{
private int score;
private int tempScore;
private int misc;
// here I have getters and setters
// A method
public int Modifier(){
return (score+tempScore-10)/2;
}
}
和
class SavingThrow{
private int base;
private int resistance;
private int bonus;
private int misc;
//Getters and setters here
//A method
public int Total(){
return base + resistance + bonus + misc;
}
}
让我们说,现在我有一个具有属性智慧和SavingThrow意志的球员A。当第一项被修改时,例如:
A.Wisdom.Score = 12;
因此,必须对第二项进行修改。在这个例子中,我应该做:
A.Will.Bonus = A.Wisdom.Modifier();
你知道怎么做到这一点吗?
我想到了下面的解决方案,但由于我将要解释的原因,它不能满足我的要求。
我不会定义getter,所以只能通过预定义的公共方法来实现对智慧的外部访问,比如SetWisdom(int得分),在这种方法中,我会更新。尽管如此,问题在于,如果我不得不修改tempScore或misc,我必须创建另一种方法来实现它。--特别是如果我向属性类添加了更多的字段,这似乎是非常没有效率的。
否则,我可以使用SetWisdom (属性智慧)方法,它将整个属性替换为一个新对象,在该对象中,我必须复制所有未修改的字段,并替换所需的字段。,这似乎有点笨拙和不雅的。你会选择哪种解决方案,更重要的是,你对如何处理这个问题有更好的想法吗?
发布于 2017-04-20 16:27:12
最简单的选择是根本不复制该值,然后您不必跟踪复制它的位置才能更新它。
class SavingThrow{
private int base;
private int resistance;
private Attribute attribute;
private int misc;
//Getters and setters here
//A method
public int Total(){
return base + resistance + attribute.Modifier + misc;
}
}
如果您在构造函数中设置了属性,那么可以这样使用您的类:
Attribute wisdom = new Attribute(16);
SavingThrow will = new SavingThrow(wisdom);
Console.WriteLine(will.Total());
wisdom.Add(2);
Console.WriteLine(will.Total());
总分应该会增加(假设在智慧中添加2会增加修饰符),因为保存抛出类从未持有副本,但直接引用了智慧。
https://stackoverflow.com/questions/43524804
复制相似问题