我想使用'[]'来检查字符串是否存在于数组中
本文关键字:于数组 存在 是否 数组 检查 字符串 | 更新日期: 2023-09-27 18:03:59
目前我的代码是这样的
public class ExampleClass
{
private static string[] words = new string[] { "Word1","Word2","Word3","Word4","Word5" };
public static bool IsExist(string Word)
{
return words.Any(w => w == Word);
}
}
我称它为
ExampleClass.IsExist("Word1"); //Returns true
ExampleClass.IsExist("WordNotExist"); //Returns false
但是我想这样调用
ExampleClass.IsExist["Word1"]; //Returns true
ExampleClass.IsExist["WordNotExist"]; //Returns false
我应该如何修改我的类来做到这一点请帮助我
我认为你在这里真的很糟糕,因为使用索引器调用方法是错误的。这样,你就不能在静态类上使用索引器了。
也就是说,它是这样工作的:
public class ExampleClass
{
public class IsExistHelper
{
private static string[] words = new string[] { "Word1", "Word2", "Word3", "Word4", "Word5" };
public bool this[string Word]
{
get
{
return words.Any(w => w == Word);
}
}
}
public static IsExistHelper IsExist { get; } = new IsExistHelper();
}
我已经使用了一个内部类来创建一个助手,它创建了你的属性名。里面有一个索引器,里面有你的原始代码。
不知道为什么要这样做,但是:
public class ExampleClass
{
private string[] words = new string[] { "Word1", "Word2", "Word3", "Word4", "Word5" };
public bool this[string Word]
{
get { return words.Any(w => w == Word); }
}
}
必须通过实例调用:
var _ = new ExampleClass();
var isTrue = _["Word1"] == true
不幸的是,不能对static
成员这样做。或者,您需要在实例名为IsExist
的辅助类中创建一个索引器。
我的意见是你应该让它保持原样。
要完全按照您想要的方式实现它(即使在我看来这不是一个好的设计),使用一个内部类,它将覆盖[]
操作符并检查您的条件。然后在你原来的类中有一个内部类的属性。
请记住,当覆盖[]
操作符时,不能使用静态类。
你可以用Contains
代替Any
,因为你是在检查整个对象本身这是一种更简洁的方法
public static class ExampleClass
{
public class InnerIsExist
{
private string[] words = new string[] { "Word1", "Word2", "Word3", "Word4", "Word5" };
public bool this[string word]
{
get { return words.Contains(word); }
}
}
public static InnerIsExist IsExist { get; } = new IsExistClass();
}
使用:
var doesItContain = ExampleClass.IsExist["b"]; // false
目前,你正在调用一个函数,它就像声明它一样简单,但是对于方括号,你将不得不重载它们。这里有一个有用的链接:如何在c#中重载方括号操作符?
基本上,在你的例子中应该是这样的:
public bool this[string Word]
{
get { return words.Any(w => w==Word); }
}
我还没有测试代码,所以让我知道它是否有效。