gma*_*ess 2 c# arrays scope if-statement
我是C#的新手,但我知道我应该能够解决这个问题.我的搜索技巧也没有给我一个直接的答案.
我有两个存储在字符串数组中的应用程序设置(它们已从一个单独的列表中拆分).
最终,我希望运行一个代码块,条件是两个设置.
条件是:
我收到了错误
当前上下文中不存在名称"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)
您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)
归档时间: |
|
查看次数: |
744 次 |
最近记录: |