Apex - 变量

Java 和 Apex 在很多方面都很相似。 Java 和 Apex 中的变量声明也完全相同。 我们将讨论一些示例来了解如何声明局部变量。

String productName = 'HCL';
Integer i = 0;
Set<string> setOfProducts = new Set<string>();
Map<id, string> mapOfProductIdToName = new Map<id, string>();

请注意,所有变量都分配有值 null。

声明变量

您可以在 Apex 中声明 String 和 Integer 等变量,如下所示 −

String strName = 'My String';  //String variable declaration
Integer myInteger = 1;         //Integer variable declaration
Boolean mtBoolean = true;      //Boolean variable declaration

Apex 变量不区分大小写

这意味着下面给出的代码将抛出错误,因为变量"m"已被声明两次并且两者将被视为相同。

Integer m = 100;
for (Integer i = 0; i<10; i++) {
   integer m = 1; //当声明 m 时,此语句将引发错误
   again
   System.debug('This code will throw error');
}

变量的作用域

Apex 变量从在代码中声明的那一刻起就有效。 因此不允许在代码块中再次重新定义相同的变量。 此外,如果您在方法中声明任何变量,则该变量范围将仅限于该特定方法。 但是,可以在整个类中访问类变量。

示例

//声明变量Products
List<string> Products = new List<strings>();
Products.add('HCL');

//不能再次在此代码时钟或子代码块中声明该变量
//如果你这样做,那么它将抛出错误作为作用域中的前一个变量
//如果在同一代码块中声明以下语句将抛出错误
List<string> Products = new List<strings>();