c#数组问题;不能将数组索引保存为变量
本文关键字:数组 保存 变量 索引 不能 问题 | 更新日期: 2023-09-27 18:04:56
我这里有这段代码用来检测某人是男性还是女性。从本质上讲,我们有一款软件,可以通过电话将我们与不同的人联系起来,并且他们的名字随时可以获得。这应该(理论上)做的是检测数组中的人的姓名和性别,并将其输入到表单中。我在这里包含了一个代码的小样本,特别是不能工作的部分,我想知道你们中是否有人知道为什么会出现这种情况。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GenderChecker
{
class Class
{
public static void Check(string stringy)
{
int gender = 0;
string[] arrayexample = { "Example One Male", "Example Two Female" };
if (arrayexample.Contains(stringy))
{
int arrayPosition = arrayexample.IndexOf(arrayexample, stringy); //part that doesn't work
}
}
static void Main(string[] args)
{
genderChecker("Example One");
}
}
}
谁能告诉我另一种保存数组位置为整数的方法,因为这段代码根本不起作用,有点令人恼火。
谢谢你,MTS
IndexOf()是Array类的静态方法。
这样做:
arrayPosition = Array.IndexOf(arrayexample, stringy);
如果字符串不在数组中,它将返回-1
你的代码将循环两次;使用for循环不是更好吗?
public static void Check(string stringy)
{
int gender = 0;
string[] arrayexample = { "Example One Male", "Example Two Female" };
var arrayPosition = -1;
for (var i = 0; i < arrayexample.Length; i++)
{
if (arrayexample[i] == stringy)
{
arrayPosition = i;
break;
}
}
}
public static void Check(string stringy)
{
int gender = 0;
string[] arrayexample = { "Example One Male", "Example Two Female" };
for(int I=0;i<arrayexample.Length;i++)
{
if (arrayexample[i].Contains(stringy))
{
int arrayPosition = i; //part that doesn't work
}
}
}
试试这个。不需要在Indexof
中包含数组参数。int arrayPosition = arrayexample.IndexOf(string);
根据您的注释,您实际上并没有试图在数组中查找字符串。你实际上试图做的是将字符串映射到性别。你使用了完全错误的工具来完成这项任务(并且使你的生活变得困难)。字典将值映射到其他值;他们正是你所需要的。
public enum Gender { Male, Female }
private Dictionary<string, Gender> _mapping = new Dictionary<string, Gender> {
["Name One"] = Gender.Male,
["Name Two"] = Gender.Female,
};
// now do something with _mapping[name]