public static void test() {
int x = 5;
x = x + 5;
System.out.print(x);
}
每当我调用功能测试并打印x
时,它总是会5
。我需要声明变量x
,以便第一次打印5
,然后10
,然后5
等?
答案 0 :(得分:2)
变量x
在方法范围内定义,因此将始终新创建,稍后将被丢弃。
public static void test() {
int x = 5;
x = x + 5;
System.out.print(x);
}
将变量放在更大的范围内(此示例中最简单的方法是将其放在方法之前):
static int x = 5;
public static void test() {
x = x + 5;
System.out.print(x);
}
BUT:
static
,除非有充分的理由。x = x + 5
缩短为x += 5
x
(方法的副作用),至少要为该方法找到一个好名称。答案 1 :(得分:2)
这应该按照您的意图工作,但是您应该始终考虑确实是否需要可以修改的静态变量。
Executables executables = pkg.Executables;
ForEachLoop forEachLoop = executables.Add("STOCK:ForEachLoop") as ForEachLoop;
forEachLoop.Name = group.ToString();
PrecedenceConstraint constraint = pkg.PrecedenceConstraints.Add(mainPipe, forEachLoop);
// Create a VariableMappings and VariableMapping objects.
ForEachVariableMappings forEachVariableMappings = forEachLoop.VariableMappings;
ForEachVariableMapping forEachVariableMapping = forEachVariableMappings.Add();
forEachVariableMapping.VariableName = @"User::ClientName";
forEachVariableMapping.ValueIndex = 0;
ForEachVariableMapping forEachVariableMapping2 = forEachVariableMappings.Add();
forEachVariableMapping2.VariableName = @"User::LinkedServer";
forEachVariableMapping2.ValueIndex = 1;
ForEachEnumeratorInfo forEachEnumeratorInfo = app.ForEachEnumeratorInfos["Foreach ADO Enumerator"];
ForEachEnumeratorHost forEachEnumeratorHost = forEachEnumeratorInfo.CreateNew();
forEachEnumeratorHost.CollectionEnumerator = true;