在构造函数C#中使用参数

时间:2015-08-19 13:23:08

标签: c# variables parameters constructor

我是新的C#。我有一些像这样的代码:

namespace Example
{
    public partial class Example_Setting : Form
    {
        public Example_Setting(String somethings)
        {
        }
        private myPlace()
        {
             MessageBox.Show(somethings);
        }
    }

我不知道如何在somethings中获取myPlace()变量的值。我该怎么办?

3 个答案:

答案 0 :(得分:4)

一个例子是:

namespace Example
{
    public partial class Example_Setting : Form
    {
        string somethings; // <-- declare a variable in the class
        public Example_Setting(String somethings)
        {
              this.somethings = somethings; // save param to variable
        }
        private myPlace()
        {
             MessageBox.Show(somethings); // now data is here for use
        }
    }

答案 1 :(得分:1)

我认为你可以使用下面的代码。解析另一个变量并将其分配给constructore然后你可以在整个类中使用它。

  public partial class Example_Setting : Form
 {
   public string some;
    public Example_Setting(String somethings)
    {
       this.some = something;
    }
    private myPlace()
    {
         MessageBox.Show(this.some);
    }
}

答案 2 :(得分:1)

其他人已经证明了一个例子。我只是想指出为什么你无法从 myPlace 访问 somethings

在您的问题中提供的示例中, somethings 的范围是locally到构造函数。也就是说,一旦构造函数完成, somethings 就不再可用于引用和使用。在其他人提供的示例中,它们将 somethings 范围限定在类中,然后分配构造函数参数中提供的值。由于 somethings 是作用于该类的,因此您的其他方法(和属性)可以访问它。请注意,如果您使用public,则该类之外的其他人也可以使用它。但最佳做法是将其保密,如果您需要公共访问权限,则使用财产。