为什么在构造函数内部声明和初始化的变量在外部已使用相同名称声明时被视为不同的变量?

Why is a variable declared and initialized inside a constructor treated as a different variable when it's already declared outside with the same name?

我只是好奇...当一个变量在构造函数外部和构造函数内部声明和初始化时,如果我们声明和初始化一个具有相同名称的变量被视为一个新的但不同的变量在构造函数?

为什么当同名变量再次声明时,它被视为不同的变量,为什么构造函数让变量被再次声明returns构造函数外部的错误?

请检查我的代码。理解我的问题

using System;

namespace Modifier
{
    public class weird
    {
       //variable name I is declared and initialized to int type value 5
       public int i = 5;

       public weird()
       {
            //same variable name i is declared and initialized to int type value 1
            int i = 2;
            //variable i which is in the scope of the constructor is displayed
            Console.WriteLine("Variable inside the constructor: "+i);
        }

        public void display()
        {
            //display() is used to display i of the class weird
            Console.WriteLine("Result:"+i);
        }
    }
 
    class Program
    {
        static void Main(string[] args)
        {
            //example object created 
            var example = new weird();
            //example object is used to display the value of i with the help of display().
            example.display();         
        }
    }
}

输出请看图

Output

局部变量有自己的scope。如果他们不这样做,所有 变量名称都必须是唯一的,如果您在一个大团队中,这将是一个很大的负担。

如果要访问成员变量而不是局部变量,请限定引用,例如this.

public  weird()
{
    int i = 2;

    Console.WriteLine("Variable inside the constructor: {0}", i);
    Console.WriteLine("Variable inside the class: {0}", this.i);
}