为什么“是”方法不运行?
c#
我有这段代码应该接受变量usersResp,看看它是否与yes数组中的元素(即在Yes方法中)匹配并打印出变量Case。根据匹配,0如果没有匹配(数组中没有与 相同的元素usersResp)或者1元素匹配,则应该是。
这是代码。
static void Main(string[] args)
{
string usersResp = "y";
int Case = 0;
Yes(usersResp, Case);
Console.WriteLine(Case);
}
static void Yes(string UserResponse, int Case)
{
string[] yes = new string[] { "y", "Y", "Yes", "yes", "yup", "Yup", "ok", "Ok", "Alright", "alright", "yeah", "Yeah", "Sure", "sure", "of course", "Of course", "k", "K" };
for (int i = 0; i < yes.Length; i++)
{
if (UserResponse == yes[i])
{
Case = 1;
return;
}
}
}
我无法弄清楚为什么它运行不正确并且Case始终保持为 0。请帮忙。谢谢。
回答
不考虑任何其他概念或其他问题。
您将需要int case通过引用传递,而不是值
static void Yes(string UserResponse, ref int Case)
其他资源
通过引用传递参数
当在方法的参数列表中使用时,ref 关键字表示参数是通过引用传递的,而不是通过值传递的。ref 关键字使形参成为实参的别名,实参必须是变量。换句话说,对参数的任何操作都是对参数进行的。
另一种方法是将 aHashSet与字符串 comparer 一起使用。只需使用Contains. 在下面的示例中,我使用StringComparer.InvariantCultureIgnoreCasewhich 将不区分大小写
public static HashSet<string> YesHashSet = new(
new[] { "y", "yes", "yup", "ok", "alright", "Yeah", "sure", "of course", "K" },
StringComparer.InvariantCultureIgnoreCase);
...
public static bool IsYes(string userResponse)
=> YesHashSet.Contains(userResponse);
更多资源
HashSet<T> 班级
代表一组值。
HashSet<T>(IEnumerable<T>, IEqualityComparer<T>)
初始化 HashSet 类的新实例,该实例使用集合类型的指定相等比较器,包含从指定集合复制的元素,并且有足够的容量来容纳复制的元素数。
StringComparer.InvariantCultureIgnoreCase Property
获取一个 StringComparer 对象,该对象使用不变区域性的单词比较规则执行不区分大小写的字符串比较。
- It would be far better to return the new value than modify the variable through side-effects
回答
我会这样处理:
static void Main(string[] args)
{
string usersResp = "y";
int Case = Yes(usersResp);
Console.WriteLine(Case);
}
static int Yes(string UserResponse)
{
string[] yes = new string[] { "y", "Y", "Yes", "yes", "yup", "Yup", "ok", "Ok", "Alright", "alright", "yeah", "Yeah", "Sure", "sure", "of course", "Of course", "k", "K" };
for (int i = 0; i < yes.Length; i++)
{
if (UserResponse == yes[i])
{
return 1;
}
}
return 0;
}
- change return type to int 🙂