【发布时间】: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();
}
}
}
输出请参考图片。
【问题讨论】:
-
为什么?因为这就是语言的设计方式以及名称解析规则的工作方式。 en.wikipedia.org/wiki/Variable_shadowing
-
这没什么奇怪的。每种支持 OOP 的语言都以这种方式工作。
标签: c# variables constructor scope clr