简体   繁体   English

如何从C#中的方法访问构造函数中的变量

[英]How do I access a variable in a constructor from a method in C#

I would like to access a variable (an array) declared inside a constructor from a method. 我想从方法访问构造函数内部声明的变量(数组)。 How would I achieve that? 我将如何实现? In the below example, I would like to use the variable 'a'. 在下面的示例中,我想使用变量“ a”。

public example(int x)    
{  
    int[] a = new int[x];
}  

public void method()  
{
    for (int i = 0; i < a.Length; ++i)
    {
        // the usage of `a`
    }
}

I would create a private field for a like: 我想创建一个私有字段为a ,如:

private readonly int[] _a;

public Example(int x)
{
   _a = new int[x];
}


public void method()
{
   for(int i = 0; i < _a.Length; ++i)
   // Rest of your code
}

please note that if you would like to modify _a after its construction, you have to remove readonly . 请注意,如果要在_a构造后对其进行修改,则必须删除readonly

Method to achieve is declare it as property of that class. 实现的方法是将其声明为该类的属性。 In constructor you should initialize private properties. 在构造函数中,您应该初始化私有属性。 So the code would look like this: 因此,代码如下所示:

    private int[] _a {get; set;}
    public example(int x)
    {
        int[] a = new int[x];
        _a = a;
    }

    public void method()
    {
        for (int i = 0; i < a; ++i)

In your code, the scope of variable 'a' is only until the end of constructor as you declared it inside the constructor. 在您的代码中,变量“ a”的作用域仅在您在构造函数内部声明时才直到构造函数结束。 If you want to use the variable 'a' outside the constructor, you should declare it outside the constructor but within the scope of the class. 如果要在构造函数之外使用变量“ a”,则应在构造函数之外但在类范围内声明它。

class example
{
   private int[] a;
   public example(int x)    
   {  
      a = new int[x];
   }  

   public void method()  
   {
      for (int i = 0; i < a.Length; ++i)
      {
         // the usage of `a`
      }
   }
}

It is suggested to declare this variable as a private member so that it cannot be assigned outside the class directly. 建议将此变量声明为私有成员,以便不能直接在类外部分配它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM