如何在c#中从public方法访问局部变量到private方法

时间:2017-01-16 09:25:12

标签: c# variables

我是c#的新手。我想使用我在public方法中声明的变量到private方法。我试过但我无法访问。有人可以帮助我吗?

[TestMethod, MNUSystemTest(TestAreas.UIAcceptance)]
[Description("TODO")]
public void TemplateTest()
{
  var matAcc = AccountManager.New<MatAccount>("MatAccount.xml")
    .WithUserNamePrefix("mat")
    .AddWithoutWorkflow();
  var matAccDisplayName = AccountManager.FormatDisplayName(matAcc);
  var matAccFriendlyDisplayName = AccountManager.FormatDisplayName(matAcc, friendly: true);
}

在上面的代码中我想使用'matAcc'变量值来测试辅助方法,即私有方法

private void CreateTestAccounts(string optionMask)
{
  depAcc1 =
    AccountManager.New<DepartmentAccount>("DepartmentAccount.xml")
      .WithUserNamePrefix("dep" + optionMask)
      .WithAncestor(matAcc)
      .AddWithoutWorkflow();
}

2 个答案:

答案 0 :(得分:0)

在方法之间使用变量是没有意义的。

想想变量的含义 - 如果它属于一个类,你应该在类中定义变量,然后它可以在该类中全局访问。

如果没有,您可能需要:

  1. 您返回结果的第一种方法(作为方法的结果,或使用&#39; out&#39;修饰符)
  2. 您的第二种方法会将此值作为参数,因此您可以在那里使用它。

答案 1 :(得分:0)

你做不到。您的matAcc变量仅在方法范围内可用。如果你想要一个变量(字段),你可以在一个类中访问和修改,你可以这样做:

class Program
{
    string global_test = "";

    public void publicMethod()
    {
        var private_test = "whatever";
        global_test = "testString";
    }

    private void privateMethod()
    {
        //cant do this
        //var testPrivate = private_test;

        var testPrivate = global_test;
    }
}
相关问题