目录

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。

Declaring Variables

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

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

Apex variables are Case-Insensitive

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

Integer m = 100;
for (Integer i = 0; i<10; i++) {
   integer m = 1; //This statement will throw an error as m is being declared
   again
   System.debug('This code will throw error');
}

Scope of Variables

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

Example

//Declare variable Products
List<string> Products = new List<strings>();
Products.add('HCL');
//You cannot declare this variable in this code clock or sub code block again
//If you do so then it will throw the error as the previous variable in scope
//Below statement will throw error if declared in same code block
List<string> Products = new List<strings>();
<上一篇.Apex - 数据类型
Apex - Strings.下一篇>
↑回到顶部↑
WIKI教程 @2018