循环内的变量声明不会重置其值

时间:2018-08-14 13:12:56

标签: vb.net

我总是给人一种印象,即在VB.NET中声明一个变量会自动将该变量设置为其数据类型的默认值(与C#不同)。

所以,之后

  • Dim intValue As Integer intValue为0
  • Dim dateValue As Date dateValue是1/1/0001
  • Dim stringValue As String stringValueNothing
  • Dim strValue As Point strValue是(0; 0)

以此类推。

但是现在我在循环中声明了一个变量,但感到惊讶的是,尽管反复声明,该变量仍保持其值。所以,

For index As Integer = 1 To 10
    Dim test As Integer

    test += 1

    Console.WriteLine(test)
Next index

输出数字1到10,而不输出数字1的十倍。

有人可以解释为什么吗?这是错误还是应该这样工作?

2 个答案:

答案 0 :(得分:2)

文档说:

  

Visual Basic每次运行Dim语句时都会将指定的值分配给该变量。如果未指定初始值,则Visual Basic在首次输入包含Dim语句的代码时会为变量的数据类型指定默认初始值。

请参阅:https://docs.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/variables/how-to-create-a-new-variable

答案 1 :(得分:-2)

我谦虚地建议您尝试一下:

<?php
$stu_result = [
  array("exam_type" => 1, "subject_id" => 5,  "converted_mark" => 5.00, "student_id" => 186, "sub_name" => "maths"),
  array("exam_type" => 1, "subject_id" => 6,  "converted_mark" => 4.00, "student_id" => 186, "sub_name" => "maths"),
  array("exam_type" => 1, "subject_id" => 7,  "converted_mark" => 5.00, "student_id" => 186, "sub_name" => "maths"),
  array("exam_type" => 1, "subject_id" => 8,  "converted_mark" => 3.00, "student_id" => 186, "sub_name" => "maths"),
  array("exam_type" => 1, "subject_id" => 9,  "converted_mark" => 4.00, "student_id" => 186, "sub_name" => "maths"),
  array("exam_type" => 1, "subject_id" => 10, "converted_mark" => 3.00, "student_id" => 186, "sub_name" => "maths"),
  array("exam_type" => 1, "subject_id" => 11, "converted_mark" => 4.00, "student_id" => 186, "sub_name" => "maths"),
  array("exam_type" => 1, "subject_id" => 12, "converted_mark" => 5.00, "student_id" => 186, "sub_name" => "maths"),
  array("exam_type" => 1, "subject_id" => 13, "converted_mark" => 4.00, "student_id" => 186, "sub_name" => "maths"),
  array("exam_type" => 1, "subject_id" => 14, "converted_mark" => 5.00, "student_id" => 186, "sub_name" => "maths"),
  array("exam_type" => 1, "subject_id" => 15, "converted_mark" => 2.00, "student_id" => 186, "sub_name" => "maths"),
  array("exam_type" => 1, "subject_id" => 16, "converted_mark" => 1.00, "student_id" => 186, "sub_name" => "maths"),
  array("exam_type" => 2, "subject_id" => 17, "converted_mark" => 5.00, "student_id" => 186, "sub_name" => "not maths"),
  array("exam_type" => 2, "subject_id" => 18, "converted_mark" => 2.00, "student_id" => 186, "sub_name" => "not maths"),
  array("exam_type" => 2, "subject_id" => 19, "converted_mark" => 5.00, "student_id" => 186, "sub_name" => "not maths"),
];
$result_exam1 = array();
foreach($stu_result as $result_temp){
  if($result_temp['exam_type'] == 1){
    $row = array( //create an array, with two values and map the values
      "converted_mark" => $result_temp['converted_mark'],
      "sub_name"  => $result_temp['sub_name']
    );
    $result_exam1[] = $row; //append to the array
  }
}
var_dump($result_exam1);
?>

或根据您的工作环境将零替换为任何空一致值。