使用IF语句更改c#上下文

时间:2018-12-01 21:14:31

标签: c#

我曾经使用过解释性语言(例如PowerShell),但是我正尝试使用c#作为一种更结构化的代码,并且老实说只是学习一些新知识。因此,在此过程中,我一直在自学,阅读许多论坛上的大量帖子,观看视频等。

似乎我缺少了一些关键的知识,这些知识会不断地以我编写的不同方法出现。活动越复杂,我看到的上下文相关问题就越多-但尽管我知道这是一个上下文相关问题,但我似乎无法弄清人们如何解决该问题(或如何向google提问以正确的方式找到问题答案)。因此,我将感谢其他人对该主题的想法,以及您可以传给我的任何智慧。

假设我有一个看起来像这样的函数:

    public PrincipalSearchResult<Principal> M2M (int credType, int actionType)
    { 
      //minor secondary question - is my return type valid?

        if (credType == 1)
        {
            PrincipalContext context = new PrincipalContext(ContextType.Machine, txtSingleServer.Text, txtAltCredID.Text, txtAltCredPW.Text);

        }
        else if (credType == 2)
        {
            PrincipalContext context = new PrincipalContext(ContextType.Machine, txtSingleServer.Text);
        }

        UserPrincipal user = new UserPrincipal(context);
        PrincipalSearcher userPrincipalSearcher = new PrincipalSearcher();
        userPrincipalSearcher.QueryFilter = user;
        PrincipalSearchResult<Principal> results = userPrincipalSearcher.FindAll();
        return results;

    }

因此,显然,我正在尝试根据传入的参数更改PrincipalContext。但是,如果在其周围放置If语句,则该方法的其余部分将不再可见。

所以...经过一番思考后,我想到了另一个主意:全局类

public static class MyGlobals
{
    PrincipalContext context = new PrincipalContext();
}

在这里,我尝试从该方法调用MyGlobals.PrincipalContext并在其中调整其值。我相信这有两个原因,这使我大吃一惊。首先,它在()中没有必需的数据,其次,从第一个方法看,它似乎不可见(即使可见同一类中的字符串)。

我认为我在这里缺少一些基本概念,但是我无法以一种可以带回此答案的方式向谷歌表达它。任何帮助将不胜感激,谢谢。

1 个答案:

答案 0 :(得分:1)

您可以将声明移至if语句之外,然后在其中设置变量。这将允许在比每个if块内部更高的范围内使用该变量。

PrincipalContext context = null;
if (credType == 1)
{
    context = new PrincipalContext(ContextType.Machine, txtSingleServer.Text, txtAltCredID.Text, txtAltCredPW.Text);

}
else if (credType == 2)
{
    context = new PrincipalContext(ContextType.Machine, txtSingleServer.Text);
}