System.String.IndexOfAny 方法 (Char[])

方法描述

报告指定 Unicode 字符数组中的任意字符在此实例中第一个匹配项的索引。

语法定义(C# System.String.IndexOfAny 方法 (Char[]) 的用法)

public int IndexOfAny(
	char[] anyOf
)

参数/返回值

参数值/返回值 参数类型/返回类型 参数描述/返回描述
anyOf System-Char[] Unicode 字符数组,包含一个或多个要查找的字符。
返回值 System.Int32 在此实例中第一次找到 anyOf 中的任意字符的索引位置(从零开始);如果未找到 anyOf 中的字符,则为 -1。

提示和注释

索引编号从零开始。

对 anyOf 的搜索区分大小写。

此方法执行顺序(不区分区域性)搜索,即,仅当 Unicode 标量值相同时两个字符才被视为相等。 若要执行区分区域性的搜索,请使用 CompareInfo.IndexOf 方法,根据所使用的区域性,该方法可能将表示预先构成字符(如连字“Æ”(U+00C6))的 Unicode 标量值视为等同于任何顺序正确的该字符的组成字符,如上述连字可能被视为“AE”(U+0041、U+0045)。

System.String.IndexOfAny 方法 (Char[])例子

下面的示例使用 IndexOfAny 方法在用户输入的字符串中检查无效字符。

/* Get the tree node under the mouse pointer and 
   save it in the mySelectedNode variable. */
private void treeView1_MouseDown(object sender, 
  System.Windows.Forms.MouseEventArgs e)
{
   mySelectedNode = treeView1.GetNodeAt(e.X, e.Y);
}

private void menuItem1_Click(object sender, System.EventArgs e)
{
   if (mySelectedNode != null && mySelectedNode.Parent != null)
   {
      treeView1.SelectedNode = mySelectedNode;
      treeView1.LabelEdit = true;
      if(!mySelectedNode.IsEditing)
      {
         mySelectedNode.BeginEdit();
      }
   }
   else
   {
      MessageBox.Show("No tree node selected or selected node is a root node.\n" + 
         "Editing of root nodes is not allowed.", "Invalid selection");
   }
}

private void treeView1_AfterLabelEdit(object sender, 
         System.Windows.Forms.NodeLabelEditEventArgs e)
{
   if (e.Label != null)
   {
     if(e.Label.Length > 0)
     {
        if (e.Label.IndexOfAny(new char[]{'@', '.', ',', '!'}) == -1)
        {
           // Stop editing without canceling the label change.
           e.Node.EndEdit(false);
        }
        else
        {
           /* Cancel the label edit action, inform the user, and 
              place the node in edit mode again. */
           e.CancelEdit = true;
           MessageBox.Show("Invalid tree node label.\n" + 
              "The invalid characters are: '@','.', ',', '!'", 
              "Node Label Edit");
           e.Node.BeginEdit();
        }
     }
     else
     {
        /* Cancel the label edit action, inform the user, and 
           place the node in edit mode again. */
        e.CancelEdit = true;
        MessageBox.Show("Invalid tree node label.\nThe label cannot be blank", 
           "Node Label Edit");
        e.Node.BeginEdit();
     }
   }
}

异常

异常 异常描述
ArgumentNullException anyOf 为 null。

命名空间

namespace: System

程序集: mscorlib(在 mscorlib.dll 中)

版本信息

.NET Framework 受以下版本支持:4、3.5、3.0、2.0、1.1、1.0 .NET Framework Client Profile 受以下版本支持:4、3.5 SP1 受以下版本支持:

适用平台

Windows 7, Windows Vista SP1 或更高版本, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008(不支持服务器核心), Windows Server 2008 R2(支持 SP1 或更高版本的服务器核心), Windows Server 2003 SP2 .NET Framework 并不是对每个平台的所有版本都提供支持。有关支持的版本的列表,请参见.NET Framework 系统要求。