gpt4 book ai didi

c# - 修改一个字段时修改另一个字段

转载 作者:行者123 更新时间:2023-11-30 21:41:19 25 4
gpt4 key购买 nike

好吧,正如标题所说,但我会更具体地说明我的情况并解释我的问题。我有以下类(class):

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,因此只能通过预定义的公共(public)方法(例如 SetWisdom(int score))对 Wisdom 进行外部访问,并在该方法中更新 Will。但是,这个问题是,如果我必须改为修改 tempScore 或 misc,我必须使用另一种方法来完成它。 这似乎很低效,特别是如果我向 Attribute 类添加更多字段。
否则,我可以使用 SetWisdom(属性智慧)方法,用一个新对象替换整个属性,我必须在其中复制所有未修改的字段并替换我需要的字段。 这似乎有点笨拙和不优雅。您会选择哪种解决方案,更重要的是,您对如何处理此问题有更好的想法吗?

最佳答案

最简单的选择是根本不复制该值,这样您就不必跟踪将其复制到何处来更新它。

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 会增加修正值),因为豁免类从未持有副本,而是直接引用智慧。

关于c# - 修改一个字段时修改另一个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43524804/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com