【问题标题】: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?为什么在构造函数内部声明和初始化的变量已经在外部以相同的名称声明时被视为不同的变量?
【发布时间】:2025-12-09 11:35:01
【问题描述】:

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

为什么把它当做一个不同的变量,为什么当同名的变量在再次声明的时候返回构造函数外的错误,构造函数又让一个变量被再次声明?

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

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

【问题讨论】:

  • 为什么?因为这就是语言的设计方式以及名称解析规则的工作方式。 en.wikipedia.org/wiki/Variable_shadowing
  • 这没什么奇怪的。每种支持 OOP 的语言都以这种方式工作。

标签: c# variables constructor scope clr


【解决方案1】:

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

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

public  weird()
{
    int i = 2;

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

【讨论】:

    最近更新 更多