在方法之后更改变量值 [英] Changing variable values after method
问题描述
感谢您过去帮助解决多个编码问题,但我又偶然发现了一个.我真的需要一些指导.
thank you for helping with multiple coding issues in the past but I've stumbled onto one more. I really need some directions on this.
在下面的脚本中,我试图在 Main
函数中调用 met1、met2 和 met3
时更改 b
的值.
In the script below, I am trying to change the value of b
when met1, met2 and met3
are called in the Main
function.
class Class3
{
public class Storage
{
public static int a = 100;
public static int b = a + 5;
}
public static void Main()
{
Methods Test = new Methods();
Console.WriteLine("Original a value: {0}", Storage.a);
Console.WriteLine("b value: {0}", Storage.b);
Test.Met1();
Console.WriteLine("After met1: {0}", Storage.a);
Console.WriteLine("b value: {0}", Storage.b);
Test.Met2();
Console.WriteLine("After met2: {0}", Storage.a);
Console.WriteLine("b value: {0}", Storage.b);
Test.Met3();
Console.WriteLine("After met3: {0}", Storage.a);
Console.WriteLine("b value: {0}", Storage.b);
}
public class Methods
{
public void Met1()
{
Storage.a -= 10;
}
public void Met2()
{
Storage.a -= 10;
}
public void Met3()
{
Console.WriteLine("{0}", Storage.a);
Met1();
Met2();
if (Storage.a > 10)
{
Met3();
}
}
}
}
根据我上面的代码,即使 a
的值发生变化,b
的值仍保持在 105.据我所知,变量 b
没有被再次调用来改变它的值.
From my code above, the value of b
stays at 105 even though the value of a
changes. From what I can tell from here, variable b
was not called again to change its value.
我应该将变量 b 作为方法并调用它吗?这只是我做的一个例子,我有超过 50 个公式,只要公式中的一个变量发生变化,就需要更改这些公式.我不认为创建 50 多个方法是个好主意,因为应该有更好的编码方式.
Should I put variable b as a method and call it? This is just an example I did and I have over 50 formulas that require changes whenever one of the variables within the formula changes. I dont think creating 50 over methods is a good idea as there should be a better way of coding this.
谢谢!
推荐答案
字段不会自动更改.这意味着b = a + 5
会将b
设置为105.每次重新计算b
的值,你可以改变它到一个属性:
Fields don't change automatically. That means that b = a + 5
will set b
to 105. To re-calculate the value of b
every time, you can change it to a property like:
public static int b => a + 5;
这样每次访问 b
时都会计算 a + 5
.
This way every time you access b
it calculates a + 5
.
这篇关于在方法之后更改变量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!