Share via


INameCreationService.ValidateName(String) 方法

定义

获取一个值,该值指示指定名称是否有效。

public:
 void ValidateName(System::String ^ name);
public void ValidateName (string name);
abstract member ValidateName : string -> unit
Public Sub ValidateName (name As String)

参数

name
String

要验证的名称。

示例

下面的代码示例提供了一个示例 INameCreationService.IsValidName 方法实现,该方法使用字符串验证方案检查指定字符串的每个字符以确定指定的字符串是否为有效名称。 如果字符串无效,方法将引发异常。

// Throws an exception if the specified name does not contain 
// all valid character types.
virtual void ValidateName( String^ name )
{
   for ( int i = 0; i < name->Length; i++ )
   {
      Char ch = name[ i ];
      UnicodeCategory uc = Char::GetUnicodeCategory( ch );
      switch ( uc )
      {
         case UnicodeCategory::UppercaseLetter:
         case UnicodeCategory::LowercaseLetter:
         case UnicodeCategory::TitlecaseLetter:
         case UnicodeCategory::DecimalDigitNumber:
            break;

         default:
            throw gcnew Exception( String::Format( "The name '{0}' is not a valid identifier.", name ) );
      }
   }
}
// Throws an exception if the specified name does not contain 
// all valid character types.
public void ValidateName(string name)
{
    for(int i = 0; i < name.Length; i++)
    {
        char ch = name[i];
        UnicodeCategory uc = Char.GetUnicodeCategory(ch);
        switch (uc) 
        {
            case UnicodeCategory.UppercaseLetter:       
            case UnicodeCategory.LowercaseLetter:     
            case UnicodeCategory.TitlecaseLetter:                                                  
            case UnicodeCategory.DecimalDigitNumber:                         
                break;
            default:
                throw new Exception("The name '"+name+"' is not a valid identifier.");                
        }
    }
}
' Throws an exception if the specified name does not contain 
' all valid character types.
Public Sub ValidateName(ByVal name As String) Implements INameCreationService.ValidateName
    Dim i As Integer
    For i = 0 To name.Length - 1
        Dim ch As Char = name.Chars(i)
        Dim uc As UnicodeCategory = [Char].GetUnicodeCategory(ch)
        Select Case uc
            Case UnicodeCategory.UppercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.DecimalDigitNumber
            Case Else
                Throw New Exception("The name '" + name + "' is not a valid identifier.")
        End Select
    Next i
End Sub

注解

INameCreationService 实现可以具有定义有效名称的参数的规则。 可以实现此方法来验证名称并强制实施这些规则。

此方法类似于 IsValidName,不同之处在于,如果名称无效,此方法将引发异常。 这允许实现者在异常消息中提供详细信息。

适用于