C#从一个作用域级别修改字符串数组

gma*_*ess 2 c# arrays scope if-statement

我是C#的新手,但我知道我应该能够解决这个问题.我的搜索技巧也没有给我一个直接的答案.

我有两个存储在字符串数组中的应用程序设置(它们已从一个单独的列表中拆分).

最终,我希望运行一个代码块,条件是两个设置.

条件是:

  1. 如果数组1(domattributes)中存在设置,请在每个设置值上运行代码.
  2. 如果数组2(intlattributes)中也存在设置,则对包含在数组1或数组中的每个设置值运行代码
  3. 下面是我尝试使用if/else语句来构建字符串数组的方法,但它不起作用.

我收到了错误

当前上下文中不存在名称"attributeIds"

我假设它是因为字符串数组实际上是在if/else语句中构建的,并且可能与尝试使用它的foreach方法的范围不同.任何帮助,将不胜感激.这是代码:

if (!string.IsNullOrEmpty(DomAttributesSetting))
{
    if (!string.IsNullOrEmpty(IntlAttributesSetting))
    {
        string[] domattributeIds = DomAttributesSetting.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
        string[] intlattributeIds = IntlAttributesSetting.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
        string[] attributeIds = new string[domattributeIds.Length + intlattributeIds.Length];
        Array.Copy(domattributeIds, attributeIds, domattributeIds.Length);
        Array.Copy(intlattributeIds, 0, attributeIds, domattributeIds.Length, intlattributeIds.Length);
    }
    else
    {
        string[] attributeIds = DomAttributesSetting.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
    }
    foreach (string attributeId in attributeIds)
    {
        PersonAttribute personAttribute = (PersonAttribute)person.Attributes.FindByID(int.Parse(attributeId));
        if (personAttribute == null)
        {
            personAttribute = new PersonAttribute(person.PersonID, int.Parse(attributeId));
        }...
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 6

attributeIds只需要声明一次,并且必须在if语句外声明它,以便它对方法的其余部分可见.

试试这个:

string[] attributeIds;
if (!string.IsNullOrEmpty(IntlAttributesSetting))
{
    string[] domattributeIds = DomAttributesSetting.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
    string[] intlattributeIds = IntlAttributesSetting.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
    attributeIds = new string[domattributeIds.Length + intlattributeIds.Length];
    Array.Copy(domattributeIds, attributeIds, domattributeIds.Length);
    Array.Copy(intlattributeIds, 0, attributeIds, domattributeIds.Length, intlattributeIds.Length);
}
else
{
    attributeIds = DomAttributesSetting.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
}

foreach (string attributeId in attributeIds)
{
    // etc...
}
Run Code Online (Sandbox Code Playgroud)